CLab's avatar
Level 3

Getting CSRF token mismatch error in production

My Laravel app doesn't through any exceptions locally but in production it seems to show a CSRF token mismatch and is shown in the error logs as follows.

 Illuminate\Session\TokenMismatchException: CSRF token mismatch.:
at .Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure} ( /workspace/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:85 )
at .Illuminate\View\Middleware\ShareErrorsFromSession->handle ( /workspace/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php:49 ) 

Now, how do I know which page is causing this in production?

Any guidance on where to start troubleshooting is appreciated.

Things I have tried so far:

  1. Adding @csrf to all form blade.
  2. App has valid SSL certificate.

Things I am thinking:

  1. Is there a way to check if axios is having trouble with the CSRF in production?
0 likes
1 reply
LaryAI's avatar
Level 58

A CSRF token mismatch error in Laravel typically indicates that the application is unable to verify the CSRF token sent with a POST request. This can happen for a variety of reasons, including session timeout, caching issues, or misconfiguration. Here are some steps you can take to troubleshoot and resolve the issue:

  1. Ensure CSRF Token is Sent with Ajax Requests: If you're using Axios or any other AJAX library, make sure that the CSRF token is included in the headers of every request. You can set this globally for Axios like so:

    axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    

    Make sure that the meta tag for the CSRF token is present in your main layout file (usually resources/views/layouts/app.blade.php):

    <meta name="csrf-token" content="{{ csrf_token() }}">
    
  2. Check Session Configuration: Verify that your session is configured correctly in config/session.php. Pay special attention to the domain and secure options, as these can affect how cookies are set and sent in production.

  3. Clear Application Cache: Sometimes, old cached views or configurations can cause issues. Clear the cache by running the following commands:

    php artisan config:clear
    php artisan cache:clear
    php artisan view:clear
    
  4. Check Middleware Order: Ensure that the VerifyCsrfToken middleware is in the correct order within your app/Http/Kernel.php. It should be in the web middleware group.

  5. Logging Additional Information: To find out which page is causing the CSRF token mismatch, you can log additional information when the exception occurs. You can override the handle method in the App\Exceptions\Handler class to include the URL and any other relevant information:

    protected function handleException($request, Throwable $exception)
    {
        if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
            // Log the URL and user information if available
            \Log::error('CSRF token mismatch on URL: ' . $request->fullUrl());
            if (auth()->check()) {
                \Log::error('User ID: ' . auth()->user()->id);
            }
        }
    
        return parent::handleException($request, $exception);
    }
    
  6. Check for Session Lifetime: If the session lifetime is too short, users might experience a CSRF token mismatch if the session expires before the form is submitted. Check the lifetime setting in config/session.php.

  7. Ensure Proper Cookie Configuration: If your application is served under different subdomains in production, ensure that the SESSION_DOMAIN variable in your .env file is set correctly to allow session cookies to be shared across subdomains.

  8. Check for Mixed Content: If your application is served over HTTPS, ensure that there are no resources being loaded over HTTP, as this can cause browsers to block cookies.

By following these steps, you should be able to identify and fix the cause of the CSRF token mismatch error in your production environment. Remember to always test changes in a staging environment before deploying to production.

Please or to participate in this conversation.