I’m building a React app with a Laravel backend (Sanctum).
In my React app, I have a Context for user authentication that makes a request to /api/user to fetch the authenticated user.
Before calling /api/user, I make sure to request /sanctum/csrf-cookie, and I see both the XSRF-TOKEN and laravel_session cookies in the browser.
Despite that, the /api/user request returns Unauthenticated.
Why would this happen even though both the CSRF token and session cookie are present?
authe context
import { createContext,useState,useEffect } from "react";
import api from "../axios";
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [user,setUser] = useState(null);
const fetchUser = async () => {
try {
const response = await api.get('/api/user');
setUser(response.data);
} catch (error) {
console.error("Error fetching user data:", error);
setUser(null);
}
}
const logout = async () => {
try {
await api.post('/api/logout');
setUser(null);
} catch (error) {
console.error("Error logging out:", error);
}
}
useEffect(() => {
api.get('/sanctum/csrf-cookie').then(fetchUser)},[]);
return (
<AuthContext.Provider value={{ user, fetchUser, logout }}>
{children}
</AuthContext.Provider>
);
}
axios file
import axios from 'axios'
const api = axios.create({
baseURL: 'http://localhost:8000',
withCredentials: true,
})
export default api
api route file
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
Route::post('/register', [App\Http\Controllers\AuthenticationController::class, 'register']);
Route::post('/login', [App\Http\Controllers\AuthenticationController::class, 'login']);
Route::post('/logout', [App\Http\Controllers\AuthenticationController::class, 'logout'])->middleware('auth:sanctum');
env file
SANCTUM_STATEFUL_DOMAINS=localhost:5173
SESSION_DOMAIN=localhost
APP_FRONTEND_URL=http://localhost:5173