I'm building a frontend in React.js and a backend in Laravel, and I'm trying to implement authentication using Laravel Sanctum.
I've set up the Laravel API, installed Sanctum, and configured the cors, sanctum middleware, and the api.php routes accordingly.
On the React side, I'm trying to make authenticated API requests after logging in, but I'm facing issues where either:
- The request gets a 401 Unauthorized
- Or the cookie is not being sent with the request
Things I've tried:
- Configured
withCredentials: truein Axios - Set
SANCTUM_STATEFUL_DOMAINSin.envto include my React app domain - Allowed CORS headers in Laravel's
cors.php
Expected:
I want to successfully authenticate and send further requests from React that are recognized by Laravel (via the session or token).
My setup:
- React (Vite) running on:
http://localhost:5173 - Laravel backend running on:
http://127.0.0.1:8000 - Sanctum config: [Insert any relevant
.envor config settings]
Axios login request example:
axios.post('http://127.0.0.1:8000/login', {
email: '[email protected]',
password: 'password'
}, {
withCredentials: true
})
I followed the official Laravel Sanctum documentation to set up authentication between my React frontend and Laravel backend.
Here's what I did:
- Installed Sanctum via Composer and ran
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" - Configured middleware: added
EnsureFrontendRequestsAreStateful::classinapi.phpmiddleware group - Set up
SANCTUM_STATEFUL_DOMAINS=http://localhost:5173andSESSION_DOMAIN=.localhostin.env - Allowed credentials and origins in
config/cors.php - Used Axios in React with
withCredentials: true - Created login and protected route in Laravel using the
auth:sanctummiddleware
What I expected:
After logging in from the React frontend, I expected:
- A cookie to be set
- Laravel to maintain session
- Authenticated requests to
api/useror other protected routes to return user data
But what I got:
- Login seems successful (no error), but the next request to a protected route returns
401 Unauthorized - The cookie doesn't appear to be set in the browser or isn’t being sent with the request