How to programmatically add a custom item to the frontend main menu?

Handle the page_block_html_topmenu_gethtml_before event and modify its menu parameter:

It has the \Magento\Framework\Data\Tree\Node type:

See also: