0

I have a problem with the Drupal cache. The cache remembers session and cookie values. Everything works fine when I'm logged in or when I completely turn off any cache.

Is it possible to use cookies and avoid they are cached for anonymous users?

0
0

First of all, you need to add the correct cache context when rendering cookie/session values. See https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts. Then you should no longer need to completely turn off caching and sessions should work fine, anonymous and logged in.

Using non-session cookies server-side can be a problem with reverse proxies in general and the built-in Internal Page Cache in specific. Disable it by triggering the kill switch on pages depending on cookies without a session:

\Drupal::service('page_cache_kill_switch')->trigger();

Don't use this trigger too often, it disables all page caching. If you need it on the majority of your pages then uninstall the Internal Page Cache, but keep the Internal Dynamic Page Cache enabled. If the dynamic page cache is too slow then put a third-party page cache in front which has the options you need to manage your cookies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.