How to handle session for anonymous users for CSRF tokens? I need to provide list of CSRF tokens in drupalSettings for every anonymous user so JS can make safe requests to api endpoints.

The CSRF service mentions the need for session to exist for the seed but I am not clear about how to create the session correctly. I tried various approaches but none seem to work correctly.

So far I have tried:

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}
// or
\Drupal::service('session_manager')-&gt;start();
// or
\Drupal::service('session_manager')-&gt;save();
// or
\Drupal::service('session_manager')-&gt;regenerate();
// or
\Drupal::service('session')-&gt;start();
// or
\Drupal::service('session')-&gt;migrate();


I am trying this in my route controller hook_page_attachments_alter.

This is my code:

/**
 * Implements hook_page_attachments_alter().
 */
function foo_page_attachments_alter(array &amp;$attachments) {
  // Needed for persistent, per-user, csrf tokens.
  $session = \Drupal::request()-&gt;getSession();
  if ($session-&gt;isStarted() === FALSE) {
    $session-&gt;start();
  }
  // or
  \Drupal::service('session_manager')-&gt;start();

  /** @var Drupal\Core\Access\CsrfTokenGenerator $csrf */
  $csrf = \Drupal::service('csrf_token');

  $attachments['#attached']['drupalSettings']['foo']['tokens'] = [
    'pathA' =&gt; $csrf-&gt;get('/pathA'),
    'pathB' =&gt; $csrf-&gt;get('/pathB')
  ];

  $session-&gt;save();
  // or
  \Drupal::service('session_manager')-&gt;save();
}
So the solution to this problem is that something has to be saved into the session :)

  if (\Drupal::service('session')-&gt;isStarted() === FALSE) {
    \Drupal::service('session')-&gt;start();
    \Drupal::service('session')-&gt;set('foo', 'bar');
  }
  \Drupal::service('csrf_token')-&gt;get('baz');


Also, there is no need to call save() method.