Certainly! This is a common issue when working with Laravel Sanctum and a separate frontend (like Next.js) on a different domain or port. The problem is related to cross-site cookies and the SameSite and Secure cookie attributes.
Why This Happens
- Browsers block cookies with
SameSite=LaxorSameSite=Strictin cross-site requests. - By default, Laravel sets
SameSite=Laxfor cookies. - If your API is on
https://your-laravel-app.testand your frontend is onhttp://localhost:3000, the browser considers this cross-site. - For cross-site cookies to work, you need
SameSite=NoneandSecure=true(i.e., HTTPS).
Solution Steps
1. Use HTTPS for Both Frontend and Backend
Browsers require Secure cookies for SameSite=None. So, both your Laravel API and your Next.js app must be served over HTTPS.
- For Laravel Herd, your app is likely already on HTTPS (e.g.,
https://your-app.test). - For Next.js, you can use mkcert or similar tools to serve it over HTTPS locally.
2. Configure Laravel's config/session.php
Set these values in your config/session.php:
'domain' => '.your-app.test', // Or null for localhost, or your custom domain
'secure' => true,
'same_site' => 'none',
Note:
- If you are using
localhost, set'domain' => null. - If you have a custom domain (e.g.,
.myapp.test), set it accordingly.
3. Configure CORS in Laravel
In config/cors.php:
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_origins' => ['https://localhost:3000'], // Use HTTPS!
'allowed_methods' => ['*'],
'allowed_headers' => ['*'],
'supports_credentials' => true,
4. Make Sure to Send Credentials in Your Next.js Requests
When making requests from Next.js (using fetch or Axios), you must send credentials:
With Axios:
axios.get('https://your-app.test/sanctum/csrf-cookie', {
withCredentials: true
});
With fetch:
fetch('https://your-app.test/sanctum/csrf-cookie', {
credentials: 'include'
});
5. Restart Your Laravel Server
After changing config files, restart Laravel Herd or run:
php artisan config:clear
Summary Checklist
- Both frontend and backend are served over HTTPS.
- Laravel's session config:
'same_site' => 'none','secure' => true. - CORS config allows your frontend origin and supports credentials.
- Next.js requests use
withCredentials: trueorcredentials: 'include'.
References
If you follow these steps, your CSRF cookie should be set correctly and authentication should work! If you still have issues, double-check the browser's network tab for cookie attributes and CORS errors.