Alter custom menu links with a session variable
The menu links defined in yaml files are static. For dynamic menu links you have to use a menu link class:

src/Plugin/Menu/CustomMenuLink.php

&lt;?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Url;

/**
 * Custom Menu Link
 */
class CustomMenuLink extends MenuLinkDefault {

  public function getTitle() {
    return $this-&gt;t('Test-Link');
  }

  public function getRouteName() {
    return 'entity.node.canonical';
  }

  public function getRouteParameters() {
    $nid = rand(1,10);
    return ['node' =&gt; $nid];
  }

  public function getCacheMaxAge() {
    return 0;
  }

}


This example is a menu link randomly selected a node between 1 and 10. For code depending on a session replace the cache max age with a context:

  public function getCacheContexts() {
    return ['session'];
  }


Point the yaml file to this class to replace the static details of the route with the dynamic methods defined in the class:

mymodule.links.menu.yml

mymodule.testlink:
  weight: 10
  menu_name: main
  class: Drupal\mymodule\Plugin\Menu\CustomMenuLink