Skip to content

Start a session on not found pages so Livewire gets a CSRF token - #394

Merged
Cannonb4ll merged 1 commit into
ploi:mainfrom
sandervanhooft:fix/livewire-csrf-on-404
Nov 16, 2026
Merged

Cannonb4ll merged 1 commit into
ploi:mainfrom
sandervanhooft:fix/livewire-csrf-on-404

Conversation

@sandervanhooft

Copy link
Copy Markdown
Contributor

Since the Livewire v4 upgrade (#392), every 404 page logs Uncaught Livewire: No CSRF token detected in the browser console.

A request to an unknown URL never matches a route, so Laravel renders the 404 page outside the web middleware group. StartSession doesn't run, csrf_token() is empty, and the layout's livewireScriptConfig ships "csrf":"". Livewire v4 throws on that, and the Livewire components on the page (such as the spotlight search) can't make requests.

Changes

  • Route::fallback(fn () => abort(404)) at the end of routes/web.php. The fallback runs inside the web group, so the 404 page gets a session and a CSRF token. It also gets the same localization and roadmap password protection as every other page. Matched routes that 404 (for example a missing model) already had a session and don't change.

The fallback route only matches GET/HEAD and always comes after every other route, and route:cache still works with it.

Tests

  • An unknown URL returns 404 and its livewireScriptConfig contains a non-empty CSRF token. The test fails without the fallback route.

A request to an unknown URL never matches a route, so it is rendered
outside the web middleware group. Without StartSession, csrf_token() is
empty and the layout's livewireScriptConfig ships "csrf":"". Since Livewire
v4 this throws "Livewire: No CSRF token detected" on every 404 page, and
the Livewire components on it (such as the spotlight search) can't make
requests.

A fallback route that aborts with a 404 runs inside the web group, so the
404 page gets a session and CSRF token, plus the same localization and
roadmap password protection as every other page.
@Cannonb4ll
Cannonb4ll merged commit 0e3cbe0 into ploi:main Nov 16, 2026
3 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.

2 participants