Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

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]:

  1. the form field _token, which the @csrf Blade directive writes[1];
  2. the X-CSRF-TOKEN header;
  3. the X-XSRF-TOKEN header, holding the value of the encrypted XSRF-TOKEN cookie 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.

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:

  • array keeps sessions in a PHP array and does not persist them[5]. Every request starts empty, so every form fails. It is meant for tests.
  • file writes to storage/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.
  • database needs a sessions table. The default users-table migration usually creates it; if not, php artisan make:session-table and php 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 a meta tag named csrf-token in your layout (Laravel’s docs print it there with the csrf_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 encrypted XSRF-TOKEN cookie, readable from JavaScript[7], and Axios and Angular copy it into the X-XSRF-TOKEN header 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.app address 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 trustProxies as 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_URL and, only if you need it, SESSION_DOMAIN in 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 (the DATA_DIR variable) 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

  1. Laravel docs — CSRF Protection (13.x) (laravel.com). Checked .
  2. Laravel docs — CSRF Protection (12.x) (laravel.com). Checked .
  3. Laravel docs — HTTP Requests, Configuring Trusted Proxies (13.x) (laravel.com). Checked .
  4. Laravel docs — HTTP Requests, Configuring Trusted Proxies (11.x) (laravel.com). Checked .
  5. Laravel docs — HTTP Session (laravel.com). Checked .
  6. Laravel docs — Configuration, configuration caching (laravel.com). Checked .
  7. Laravel source — PreventRequestForgery.php (13.x) (raw.githubusercontent.com). Checked .
  8. Laravel source — Foundation/Exceptions/Handler.php (13.x) (raw.githubusercontent.com). Checked .
  9. Laravel source — Foundation/Exceptions/views/419.blade.php (13.x) (raw.githubusercontent.com). Checked .
  10. Laravel application skeleton — config/session.php (13.x) (raw.githubusercontent.com). Checked .
  11. Laravel application skeleton — config/app.php (13.x) (raw.githubusercontent.com). Checked .
  12. Laravel source — Routing/UrlGenerator.php (13.x) (raw.githubusercontent.com). Checked .
  13. 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 app

Got a question? — @livops_uz