axespace's avatar

React + Laravel Sanctum

Hi guys. I'm facing 401 server error when i try to access my routes with auth:sanctum middleware. I really couldn't find an answer anywhere. Will be very pleased if you help me.

My env configuration looks like this:

APP_URL=http://127.0.0.1:8000
SESSION_DRIVER=file
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:3000

sanctum.php:

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

axios request:

apiClient.get('/sanctum/csrf-cookie').then(() => {
      apiClient
        .post('/api/posts', data)
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log(error);
        });
    });

apiClient:

const apiClient = axios.create({
  baseURL: 'http://127.0.0.1:8000',
  withCredentials: true,
});
0 likes
1 reply
teos_97's avatar

try setting your session driver to cookie in your .env file

SESSION_DRIVER=cookie

Make sure you also have the EnsureFrontendRequestsAreStateful api middleware set in your Kernel.


 'api' => [
…
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful
…

Finally check in your config/cors.php that you allow credentials


'supports_credentials' => true

1 like

Please or to participate in this conversation.