Search code examples
laravelnext.jslaravel-sanctum

CSRF Token Mismatched on server though it's working fine on localhost


I am working on a project (Laravel API - Sanctum & NextJs). Logging in and everything is working fine on localhost and postman but it shows 'CSRF Token Mismatched' after deploying on the server.

admin.example.com is the subdomain where I deployed the NextJs app. I updated the main domain and subdomain in sanctum.php as follows.

sanctum.php

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,localhost:8000::1,example.com, admin.example.ae',
        env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : '',
        env('FRONTEND_URL') ? ',' . parse_url(env('FRONTEND_URL'), PHP_URL_HOST) : ''
    ))),

Solution

  • I got the solution for this.

    If you are just starting to add Sanctum to your project or about to go live with Sanctum, please make sure you configured all the mentioned settings on this section of Laravel Sanctum Docs. I have mentioned them in a summary below.

    • If you are working on localhost and it has port (eg. 8000), please send the request from your frontend app to http://localhost:8000 instead of http://localhost.
    • Make sure supports_credentials is true on config/cors.php
    • Set withCredentials to true on your global Axios configuration of frontend
    • Make sure your application's session cookie domain configuration supports any subdomain of your root domain by configuring this 'domain' => '.example.com', at config/session.php file or add this SESSION_DOMAIN=".example.com" to your .env file

    As I mentioned above, please go through and read this section of Laravel Sanctum Docs again if it still doesn't work.

    If you can't even make the request from Postman, please read this thread that mentions what I experienced at the same time.