Repository navigation
Start a session on not found pages so Livewire gets a CSRF token - #394
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Since the Livewire v4 upgrade (#392), every 404 page logs
Uncaught Livewire: No CSRF token detectedin the browser console.A request to an unknown URL never matches a route, so Laravel renders the 404 page outside the
webmiddleware group.StartSessiondoesn't run,csrf_token()is empty, and the layout'slivewireScriptConfigships"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 ofroutes/web.php. The fallback runs inside thewebgroup, 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:cachestill works with it.Tests
livewireScriptConfigcontains a non-empty CSRF token. The test fails without the fallback route.