How To Connect a Nextjs front-end with a Laravel Backend With Sanctum
I liked NextJS but I liked Laravel's auth features. So I wanted to use both but struggled a bit.
Here is how I set up the app/config/cors.php. Note that I added the login and logout routes as well. Also the allowed_origins is localhost:3000 which is where normally NextJS starts.
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout', 'register'],
'allowed_methods' => ['*'],
'allowed_origins' => ['http://localhost:3000'],
'allowed_origin_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => ['*'],
'max_age' => 0,
'supports_credentials' => 0,
I installed Laravel Sanctum according to Laravel documentation
This creates a /sanctum/csrf-cookie route which you will call from your NextJS app to create the csrf-token.
Setting up my axios instance after 'npm install axios' in the NextJS application:
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;
Add this to your front-end .env
.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 set your Laravel cookie.
This will be automatically available once you install Laravel Sanctum as described above
I hope this helps.