Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chrischerrett's avatar

XSRF-TOKEN and session key change with each request

Having implemented Authentication for my SPA using Sanctum successfully, I'm finding the http response to every request returns a new value for both the XSRF-TOKEN and the session key. This doesn't seem right. Am I correct to expect this value to remain the same with every response?

As a result, each request therefore sends a new value, and the session never seems to expire as a consequence. Can't work out what's going wrong?

Everything else is working as expected, as per the docs. Any clues?

'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:180,1', \Illuminate\Routing\Middleware\SubstituteBindings::class, ],

0 likes
4 replies
fylzero's avatar

@chrischerrett I could be wrong, just guessing here without looking at it... but obviously the XSRF will change on every request, that is the point of that token, to validate requests are secure for that single request. The session key is probably just "changing" because of encryption but is actually the same under the hood. This is the part I'm guessing about. Easy way to test your session is just drop the SESSION_LIFETIME to 1 in your .env and see if it expires. If not, something is up. If it does, probs just encryption making it look like it's changing.

1 like
chrischerrett's avatar

Thanks for your reply @fylzero. I tried your suggestion regarding the expiry, by dropping it to a minute, but the session never expires.

The reason I suspected the token shouldn't change is because it doesn't with a "normal" implementation of the token, in the traditional Blade sense of storing it in the meta tag.

fylzero's avatar

@chrischerrett Maybe try messing with the config/sanctum.php Expiration Minutes setting?

Hard code that to 1 and see if it expires after a minute. Totally guessing here btw. Just trying to think of things to try.

This may actually be intended behavior of Sanctum, I'm not sure. I know it has been a practice to extend sessions from expiring in SPAs. Jess Archer spoke about this a bit at a Laracon: https://youtu.be/Zv4bUXEwl20?t=710

1 like
martinbean's avatar

The reason I suspected the token shouldn't change is because it doesn't with a "normal" implementation of the token, in the traditional Blade sense of storing it in the meta tag.

@chrischerrett The token will change after every form submission, though. Otherwise a bad actor could read the CSRF token from the head of your website, start submitting forms, and render the point of the CSRF token completely pointless.

Please or to participate in this conversation.