A note about anonymous users

If you run that chunk of code from the preceding section as an anonymous user, you'll note that the entry gets created in the database with a session ID, as expected. However, upon the next request, if you try to retrieve the value by key, you won't find it. That is because anonymous users do not necessarily have a session started. This means a new session ID is created for each request. So, how can we solve this?

The first time you start the process or flow in which you need to interact with the private tempstore, check yourself whether the current user is anonymous. If they are, dump a variable into the $_SESSION super global in order to keep the session. Otherwise, it gets erased because there is no data. So, ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.