Knowledge

419 Page Expired error in Laravel

#Laravel

When working with Laravel you will encounter this error from time to time. Here's how you can fix this error.

Published by Mark van Eijk on February 23, 2024 · 1 minute read

  1. Why is the page expired?
  2. When does this happen
  3. How to fix the error

Why is the page expired?

Laravel uses Cross-Site Request Forgery (CSRF) as a protection mechanism, that protects your app from external HTTP requests to your application.

Requests from the outside cannot always be trusted, because they can try to mingle with the data and sessions of your users.

CSRF works by generating a unique and randomly generated token that only your application knows and therefore it can detect if a request is allowed by verifying this token. The token expires automatically to make sure it cannot be retrieved and used again and again.

When does this happen

A page expired error can happen when you've forgotten to send the randomly generated CSRF token along with a "POST", "PUT", "PATCH", or "DELETE" request.

This typically happens when making an AJAX request or when submitting a form.

How to fix the error

When submitting a form, always add a hidden input named _token with the value set to csrf_token(). More easily you can use the @csrf Blade directive which is a shortcut to output this hidden input.

If you're performing an AJAX request, then it's because you've forgotten to add the X-CSRF-TOKEN header to the request.

You can add this header automatically to every AJAX request when using the popular Axios Javascript HTTP library:

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Or when using jQuery:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

Another option - depending on your use case - is to disable the verification of the CSRF token for all or specific routes in your application.

In case of stateless requests like API or webhooks this makes sense and is the use of API tokens or signed routes more suitable.

Subscribe to our newsletter

Do you want to receive regular updates with fresh and exclusive content to learn more about web development, hosting, security and performance? Subscribe now!

Related articles

How to use different PHP versions with Laravel Valet

When working with Laravel you will encounter this error from time to time. Here's how you can fix this error.

Read more →

Disable cookies in Laravel

When working with Laravel you will encounter this error from time to time. Here's how you can fix this error.

Read more →