419 Page Expired in Laravel after deploy: CSRF token mismatch, fixed
419 Page Expired is how Laravel answers a POST whose CSRF token does not match the one in the session (TokenMismatchException, CSRF token mismatch.). After a deploy it usually means the session cookie never came back: the form posts to an http:// address because Laravel does not trust the HTTPS proxy, or SESSION_DOMAIN, SESSION_SECURE_COOKIE or SESSION_DRIVER is wrong for production. Otherwise the form lacks @csrf or the AJAX call lacks X-CSRF-TOKEN.
By Livops team, the people who build and run LivopsUpdated
What the visitor sees, after pressing a form’s submit button on a freshly deployed Laravel site[9]:
419 | Page Expired
An AJAX request gets the same status with a JSON body, because Laravel turns the TokenMismatchException into an HTTP 419 that keeps the exception’s message[8][7]:
POST https://shop.example.com/cart 419
{"message": "CSRF token mismatch."}
This page explains what Laravel checks before it answers 419, lists the causes in the order they show up after a deploy, starting with the session cookie that never comes back, and shows how to test the fix with curl before you deploy again.
What does the error mean?
Laravel generates a CSRF token for every session and stores it in the session; the token changes each time the session is regenerated[1]. Every POST, PUT, PATCH or DELETE must bring it back[1]. GET, HEAD and OPTIONS are never checked[7]. The middleware looks for the token in this order[7]:
- the form field
_token, which the@csrfBlade directive writes[1]; - the
X-CSRF-TOKENheader; - the
X-XSRF-TOKENheader, holding the value of the encryptedXSRF-TOKENcookie Laravel sends with each response[1].
If the token is missing or does not match the session’s, the middleware throws TokenMismatchException('CSRF token mismatch.')[7], and the exception handler turns it into a 419[8]. The exception is on the handler’s internal do-not-report list, so nothing reaches your log by default[8]: the 419 page is all you get.
Laravel 13 checks the origin first. The middleware is now PreventRequestForgery. It first reads the browser’s Sec-Fetch-Site header; a request from the same origin is allowed without any token. It falls back to the token check for older browsers, for requests from another origin, and when the connection is not secure: browsers send that header only over HTTPS[1]. In Laravel 12 the middleware is ValidateCsrfToken and always checks the token[2]. Either way, the token path is the one that fails below.
The important consequence: the token is compared with the one in the session. If the browser does not send the session cookie back, Laravel starts a new, empty session, finds no matching token, and answers 419, even though the form had a perfectly good _token field. That is why most 419s after a deploy are session problems, not form problems.
Causes, most common first
1. Laravel does not know the request was HTTPS
A platform or reverse proxy takes the visitor’s HTTPS connection and passes the request to Laravel over plain HTTP. Laravel’s docs describe the symptom: behind a load balancer that terminates TLS, the app sometimes does not generate HTTPS links, because it is forwarded traffic on port 80 and does not know it should[3]. URLs are built with the request’s own scheme unless one is forced[12], so route('login') in a form’s action comes out as http://shop.example.com/login.
Then the chain is short. The browser submits the form to http://. A session cookie marked Secure is sent only over https:[13], so it stays behind; Laravel sees a visitor with no session, and the token in the form matches nothing.
Fix: trust the proxy. In Laravel 11 and later, trustProxies goes in bootstrap/app.php[4][3]. When you do not know the proxies’ addresses, as on a cloud platform, the docs allow *[3]:
->withMiddleware(function (Middleware $middleware): void {
$middleware->trustProxies(at: '*');
})
Laravel then reads the forwarding headers, including X-Forwarded-Proto, and the headers it trusts can be narrowed with the headers argument[3]. Trust all addresses only when the app cannot be reached except through the proxy; anyone who can reach it directly could send forged forwarding headers.
A second belt: force the scheme. UrlGenerator has forceScheme and forceHttps, which forces HTTPS for all generated URLs[12]. In AppServiceProvider::boot():
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
URL::forceHttps(App::environment('production'));
This fixes the links, but not $request->isSecure(); the proxy setting fixes both.
And APP_URL. Its default is http://localhost, and the skeleton’s comment says it is used by the console to generate URLs from Artisan[11]. Set it to the https:// address anyway, so links built from Artisan commands are right, but it does not make web requests count as HTTPS.
2. The browser rejects or does not return the session cookie
Laravel’s session cookie and the XSRF-TOKEN cookie take their domain, Secure flag and SameSite from config/session.php[7]. In the skeleton they are read from the environment[10]:
| Variable | Default | What goes wrong |
|---|---|---|
SESSION_DOMAIN |
not set | Set to a domain that does not include the site, for example localhost or the old domain. The value must be the server’s domain or a parent of it, and cookies that break the rule are ignored[13]. |
SESSION_SECURE_COOKIE |
not set | When true, the cookie is sent back only over HTTPS[10]. Right for production, but any http:// form action (cause 1) or a test over plain http:// loses the session. |
SESSION_SAME_SITE |
lax |
A Lax cookie is not sent on a cross-site POST[13], so a form on another site, or your page inside someone else’s frame, posts without it. |
For a site on one host, leave SESSION_DOMAIN empty; set it only when the session must be shared with subdomains, since the value decides the domain and subdomains the cookie is available to[10]. Keep SESSION_SECURE_COOKIE=true once every address is HTTPS.
3. The session is not stored where the next request can find it
SESSION_DRIVER decides where session data lives; the default is database[5][10]. The drivers that cause 419s in production:
arraykeeps sessions in a PHP array and does not persist them[5]. Every request starts empty, so every form fails. It is meant for tests.filewrites tostorage/framework/sessions[5]. On a platform where files next to the code are replaced at every deploy, every open form fails once after each deploy; with several copies of the app, each copy has its own files.databaseneeds asessionstable. The default users-table migration usually creates it; if not,php artisan make:session-tableandphp artisan migrate[5].
For production, database or redis[5] keeps sessions across deploys and copies of the app.
4. The configuration is cached with old values
php artisan config:cache combines the configuration into one file. Once it is cached, Laravel does not load .env during requests or Artisan commands, and env() returns only real environment variables[6]. A build step that caches the config before the production variables exist, or a cache made before you changed SESSION_DOMAIN, keeps the old values. Clear it[6]:
php artisan config:clear
and cache it again only where the final variables are set, for example in the start command. Call env() only inside config/ files; outside them it returns nothing once the config is cached[6].
5. The form has no token
Every POST, PUT, PATCH or DELETE form needs the hidden _token field; the @csrf directive writes it[1]:
<form method="POST" action="/profile">
@csrf
...
</form>
On Laravel 13 over HTTPS, a modern browser posting from the same origin passes the origin check even without it[1], so a missing @csrf may show up only for some visitors: older browsers, or a form on www. posting to the bare domain.
6. AJAX without the header
fetch sends no token by itself. Two ways, both from Laravel’s docs[1]:
-
X-CSRF-TOKEN. Put the token in ametatag namedcsrf-tokenin your layout (Laravel’s docs print it there with thecsrf_token()helper) and send it with every request:const token = document.querySelector('meta[name="csrf-token"]').content; fetch("/cart", { method: "POST", headers: { "X-CSRF-TOKEN": token, "Content-Type": "application/json" }, body: JSON.stringify(item), }); -
X-XSRF-TOKEN. Laravel sends the token in an encryptedXSRF-TOKENcookie, readable from JavaScript[7], and Axios and Angular copy it into theX-XSRF-TOKENheader on same-origin requests by themselves[1].
For a separate SPA that uses Laravel only as an API, the docs point to Sanctum instead[1].
7. The session simply expired
SESSION_LIFETIME defaults to 120 minutes[10]. A form left open longer, or one opened before a login in another tab regenerated the session[1], posts a token the session no longer has. Catch the 419 and send the visitor back to the form with a message, rather than raising the lifetime for everyone.
Excluding a route
A webhook from a payment provider cannot know your token. Put such routes outside the web middleware group, or list them in bootstrap/app.php: preventRequestForgery(except: [...]) on Laravel 13[1], validateCsrfTokens(except: [...]) on Laravel 12[2]. Do not exclude a form your visitors submit.
How to confirm the fix
Test the deployed site with a cookie jar, the way a browser posts. curl sends no Sec-Fetch-Site, so on Laravel 13 too this goes through the token check:
curl -s https://shop.example.com/login | grep -o 'action="[^"]*"' # must start with https://
curl -sI https://shop.example.com/login | grep -i '^set-cookie' # look at Domain= and Secure
curl -s -c jar.txt https://shop.example.com/login -o login.html
TOKEN=$(grep -o 'name="_token" value="[^"]*"' login.html | sed 's/.*value="//; s/"$//')
curl -s -b jar.txt -o /dev/null -w '%{http_code}\n' -X POST https://shop.example.com/login \
--data-urlencode "_token=$TOKEN" -d "[email protected]" -d "password=wrong"
The last line must print anything but 419: a redirect back with a validation error is the expected answer. If it prints 419 even with the token and the cookie, the session did not survive between the two requests: look at the driver (cause 3) and the cached config (cause 4). If the form’s action starts with http://, go back to cause 1.
On Livops
- Every address is HTTPS. The project’s
<name>.livops.appaddress gets HTTPS automatically, and a domain you connect gets its certificate as soon as it is live. Laravel and plain PHP are among the detected frameworks. - Trust the proxy only on evidence. Add
trustProxiesas in cause 1 after you have checked which header reaches your app: log$request->header('X-Forwarded-Proto')once, or print$request->isSecure()on a test route. - Session settings in Variables. Set
SESSION_DRIVER,SESSION_SECURE_COOKIE,APP_URLand, only if you need it,SESSION_DOMAINin the service’s Variables. New values take effect on the next deploy; to apply them now, restart the service. If you cache the config yourself, do it in the start command, where these variables are present. - Keep sessions off the code folder. While the app runs, its code is read-only, and files written next to the code are gone after the next deploy; only
/app/data(theDATA_DIRvariable) is kept. Store sessions in a database: a Redis of the Cache type is meant for sessions and caches, and the connection variables are written to your service when you connect one. - Where to look. The 419 itself is not logged by Laravel, so add a log line in your exception handler while you debug; the app’s output is on the project’s Logs page.
What Livops does for PHP: Frameworks. The other error that follows a missing variable: No application encryption key has been specified. If the browser console also says Mixed Content, the same proxy setting is behind it: Mixed Content: requested an insecure resource.
Questions
What does 419 Page Expired mean in Laravel?
Laravel's CSRF middleware found no token in the request, or a token that does not match the one stored in the visitor's session, and threw a TokenMismatchException with the message CSRF token mismatch. Laravel turns that exception into an HTTP 419 response, and its error page says Page Expired.
Why do forms work locally and fail with 419 after deploy?
Locally the browser and Laravel both use http://localhost, so links, cookies and the session agree. In production the visitor uses HTTPS while Laravel behind a proxy may see plain HTTP, build the form's action with http://, and the browser then leaves the secure session cookie out. Production also brings new session settings: another driver, a cookie domain, a secure flag, a cached config.
Should I just exclude the route from CSRF protection?
Only for a route that is called by another service, such as a payment webhook that cannot know your token. For a login or checkout form, excluding it removes the protection instead of fixing the session, and the session problem will break logins next.
Is it safe to trust all proxies with an asterisk?
Laravel's docs suggest it when you do not know the addresses of your load balancers, as on a cloud platform. It is reasonable when the app can only be reached through that proxy. If visitors could reach the app directly, they could send forged forwarding headers.
I changed SESSION_DOMAIN and nothing happened. Why?
If the configuration was cached with php artisan config:cache, Laravel does not read .env during requests, so the old value stays. Run php artisan config:clear, or cache again where the new values are set, and restart or redeploy the app.
Why do I get 419 only when a form has been open for a long time?
The session expired. By default the session lifetime is SESSION_LIFETIME, 120 minutes, and after that the token in the old form matches nothing. The token also changes whenever the session is regenerated, for example at login in another tab.
What does Livops do for a Laravel app?
It detects Laravel, builds and runs it, and serves every address over HTTPS, the livops.app one and your own domain. Session settings are yours: set SESSION_DRIVER and the other variables in the service's Variables, and deploy again after changing them.
Sources
- Laravel docs — CSRF Protection (13.x) (laravel.com). Checked .
- Laravel docs — CSRF Protection (12.x) (laravel.com). Checked .
- Laravel docs — HTTP Requests, Configuring Trusted Proxies (13.x) (laravel.com). Checked .
- Laravel docs — HTTP Requests, Configuring Trusted Proxies (11.x) (laravel.com). Checked .
- Laravel docs — HTTP Session (laravel.com). Checked .
- Laravel docs — Configuration, configuration caching (laravel.com). Checked .
- Laravel source — PreventRequestForgery.php (13.x) (raw.githubusercontent.com). Checked .
- Laravel source — Foundation/Exceptions/Handler.php (13.x) (raw.githubusercontent.com). Checked .
- Laravel source — Foundation/Exceptions/views/419.blade.php (13.x) (raw.githubusercontent.com). Checked .
- Laravel application skeleton — config/session.php (13.x) (raw.githubusercontent.com). Checked .
- Laravel application skeleton — config/app.php (13.x) (raw.githubusercontent.com). Checked .
- Laravel source — Routing/UrlGenerator.php (13.x) (raw.githubusercontent.com). Checked .
- MDN — Set-Cookie header (developer.mozilla.org). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your Laravel appRelated
- Mixed Content: the page was loaded over HTTPS, but requested an insecure resource — fix after deployMixed Content: The page at 'https://…' was loaded over HTTPS, but requested an insecure resource 'http://…'. This request has been blocked means your HTTPS page asked for a script, stylesheet or API call over plain http://, and the browser refused. After a deploy the usual reasons are an API address with http:// baked into the frontend build, or a backend behind an HTTPS proxy that builds its URLs with http://. Use https:// or relative URLs, rebuild, and make the backend trust its proxy.
- Laravel hosting with queues and the scheduler: the options comparedA Laravel app in production is three processes: the web server, a queue worker that is restarted on every deploy, and the scheduler run every minute. On Livops the web app runs from a push with APP_KEY generated and migrations run, for 39 credits a month (39,000 so'm), and the worker and the scheduler are services of their own at 19 credits each. Here is how Render, Railway, Fly.io and a VPS compare.
- Laravel: No application encryption key has been specifiedLaravel's encrypter has no key, because the APP_KEY environment variable is empty on the server. Generate one with php artisan key:generate --show, set it as APP_KEY where the app runs, clear any cached configuration, and keep the same key from then on.
- PHP hosting in 2026: how to deploy a PHP app or siteA PHP project is recognised from index.php or composer.json, its dependencies are installed, and it is served by FrankenPHP on the port Livops assigns. A plain folder of PHP files needs no configuration at all.
- Forbidden (403) CSRF verification failed. Request aborted. — Django after deployForbidden (403) CSRF verification failed. Request aborted. means Django's CSRF middleware refused a POST. Right after moving behind HTTPS and a proxy, the usual reason is Origin checking failed: add the site's origin with its scheme, such as https://example.com, to CSRF_TRUSTED_ORIGINS. For CSRF cookie not set or CSRF token missing, put the csrf_token tag in the form or send the X-CSRFToken header.
- Laravel: The stream or file laravel.log could not be opened in append mode: Permission deniedThe stream or file "storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied means the PHP process cannot write Laravel's log file: storage is owned by another user, the file was created by root, or the code runs on a read-only filesystem. Make storage and bootstrap/cache writable by the PHP user, or in a container log to stderr with LOG_CHANNEL=stderr. The bootstrap/cache directory must be present and writable is the same problem one folder over.