Skip to content

[6.x] Wait for the csrf request before the nocache request - #15994

Merged
jasonvarga merged 1 commit into
statamic:6.xfrom
theluckystrike:fix/nocache-waits-for-csrf
Nov 23, 2026
Merged

jasonvarga merged 1 commit into
statamic:6.xfrom
theluckystrike:fix/nocache-waits-for-csrf

Conversation

@theluckystrike

Copy link
Copy Markdown
Contributor

Fixes #15643

On a fully cached page the csrf script (in <head>) and the nocache script (before </body>) both send a POST as soon as they run. On a first visit the browser has no session cookie yet, so each request starts its own session. The page keeps the token from /!/csrf, but the browser keeps the session cookie from whichever response arrives last. When /!/nocache answers last, the token and the cookie belong to different sessions and the form POST returns 419 (on Laravel 12, or Laravel 13 without HTTPS, where the token check is used).

This change keeps the csrf request in window.statamicCsrfRequest and makes the nocache script wait for it before it sends its own request. The nocache request then carries the session cookie from the csrf response, so both responses use the same session. If there is no csrf script on the page (or a custom one from setCsrfTokenJs), Promise.resolve(undefined) resolves at once and nothing changes. A failed csrf request does not block the nocache request.

The cost is that on pages with both scripts the nocache request starts after the csrf response instead of in parallel.

Tests

  • New FileCacherTest::nocache_request_waits_for_the_csrf_request, fails on 6.x and passes with the change.
  • vendor/bin/phpunit tests/StaticCaching/ passes (272 tests), pint passes.
  • I also ran both default scripts in Node with a fake fetch that starts a new session for every request without a cookie. With the csrf response first and the nocache response last, 6.x ends with cookie s2 and token s1 (mismatch). With the change both requests use s1.

@jasonvarga
jasonvarga merged commit bbc68a5 into statamic:6.x Nov 23, 2026
62 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Static caching: /!/csrf and /!/nocache race on first visit, page token and session cookie come from different sessions, form POST returns 419

2 participants