[Solved] CSRF Token Mismatch Error from API Laravel Sanctum

Updated: 14th April 2024
Tags: php laravel sanctum

If you are using laravel sanctum and from localhost frontend spa try request API you can receive this error CSRF Token Mismatch.

This happens because sanctum has configuration to use session for local development instead of tokens.

There are two methods to solve it:

Method #1

Add in .env file SANCTUM_STATEFUL_DOMAINS=

Pros:

  1. You can change it through .env file and have on different instances (dev/stage/prod) different settings.

Cons:

  1. You need to remember to add this to .env file where you don’t need stateful (session auth) to api endpoints.

Method #2

Edit config/sanctum.php file and change stateful to

'stateful' => [],

Pros:

  1. You change it and everything is using token based auth in every instance of your app. You don’t have to do anything more.

Cons:

  1. If you need stateful (session auth) to api on some domains - well now you can’t.

What method to choose?

If your app is using only tokens, imo the easiest will be to turn off completely using method 2. If you need on some domains to have stateful (session) based auth, use method 1.