Hitesh Chauhan
Hitesh Chauhan

Reputation: 1082

Laravel 8 sanctum api "CSRF token mismatch" 419 error with next.js app

I am getting the message: "CSRF token mismatch. error while using laravel sanctum api with Next.js app.

POST https://xyzdomain.api/login 419

Uncaught (in promise) Error: Request failed with status code 419
at e.exports (7269-1f09c32afb5696ba.js:1:5531)
at e.exports (7269-1f09c32afb5696ba.js:1:7980)
at XMLHttpRequest.g (7269-1f09c32afb5696ba.js:1:782)

Everything is working fine on localhost, but getting the above error while I make the app live on the production server.

Upvotes: 4

Views: 6529

Answers (1)

Ronodip Basak
Ronodip Basak

Reputation: 118

You need to get csrf cookie first. As per laravel's documentation :

To authenticate your SPA, your SPA's "login" page should first make a request to the /sanctum/csrf-cookie endpoint to initialize CSRF protection for the application

This request will return a set-cookie header to set CSRF Token in the cookie.

!------ This is not recommend for web app. But may be of value to some -------!

Also, if you choose to (NOT RECOMMENDED), you can disable CSRF validation for api routes. Just modify app/Http/Middleware/VerifyCsrfToken.php to add /api/* inside the $except array. It should look something like this:

    protected $except = [
        '/api/*'
    ];

Upvotes: 1

Related Questions