How To Connect a Nextjs front-end with a Laravel Backend With Sanctum

Here is how I set up the app/config/cors.php. Note that I added the login and logout routes as well

app/config/cors.php

'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout', 'register'],

'allowed methods' => ['*'],

'allowed_origins' => ['http://localhost:3000'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

I installed Laravel Sanctum according to Laravel documentation

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Setting up my axios instance after 'npm install axios'

import Axios from 'axios'

const axios = Axios.create(❴

baseURL: process.env.NEXT_PUBLIC_BACKEND_URL,

headers: ❴

"X-Requested-With": "XMLHttpRequest"

❵,

withCredentials: true

❵)

export default axios;

.env

NEXT_PUBLIC_BACKEND_URL="http://localhost:8000"

You will need to call the /sanctum/csrf-cookie endpoint from your nextjs application in laravel to set the authentication cookie

This will be automatically available once you install Laravel Sanctum as described above

I hope this helps.