Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

abdul_rehman333's avatar

Laravel Sanctum + Nuxt.js SSR: Session Authentication Not Persisting After Login

Problem Summary I have a Laravel backend with Nuxt.js frontend using Laravel Sanctum for session-based authentication. The login works and returns the user correctly, but when I try to access protected routes immediately after, the user appears as "not authenticated". My Setup

Backend: Laravel 11 with Sanctum (session-based auth) Frontend: Nuxt.js 3 with SSR enabled (running on localhost:3000) Backend: Running on localhost:8000 Session Driver: Database Authentication Flow: Register → Email Verification → Login → Access Protected Routes

What's Working

✅ Registration works fine ✅ Email verification works and logs user in ✅ Login endpoint returns user data correctly ✅ Session is created in database ✅ Debug response shows auth_check: true and correct user_id

What's Not Working ❌ After successful login, when I call /api/v1/user/me, it returns "User not authenticated" Debug Information Login Response (Working) json{ "success": true, "message": "Login successful.", "user": { "id": 1, "name": "John Doe", "email": "[email protected]" }, "debug": { "auth_check": true, "user_id": 1, "session_id": "wLBvSzvsBqaNl5Mmv8ms7iS0NacDbft1B0NiFNCq" } } /me Endpoint Call (Not Working) Laravel Log: [2025-06-13 13:02:39] local.INFO: === /me endpoint called === { "session_id": "v3oOvhWNKxqNXe4sRDBOwQRwreKm2AgZZZhmfS3y", // Different session ID! "auth_check": false, "user_id": null, "session_data": [], "cookies": [] // No cookies being sent! } Key Issues Identified

Different Session IDs: Login creates session wLBvSzv... but /me call uses v3oOvh... No Cookies: The /me request shows "cookies": [] - no session cookies being sent New Session Each Time: Every request creates a new session instead of using existing one

Current Configuration Laravel .env envSESSION_DRIVER=database SESSION_LIFETIME=120 SESSION_ENCRYPT=false SESSION_PATH=/ SESSION_DOMAIN=null SESSION_SECURE=false SESSION_HTTP_ONLY=true SESSION_SAME_SITE=lax

SANCTUM_STATEFUL_DOMAINS="localhost:3000,127.0.0.1:3000" CORS Configuration (config/cors.php) phpreturn [ 'paths' => ['api/', 'sanctum/csrf-cookie'], 'allowed_methods' => [''], 'allowed_origins' => ['http://localhost:3000'], 'allowed_headers' => ['*'], 'supports_credentials' => true, ]; Routes (routes/api.php) php// Public routes Route::middleware(['web'])->group(function () { Route::post('v1/user/login', [AuthController::class, 'login']); Route::post('v1/user/verify-register', [AuthController::class, 'verifyRegistration']); });

// Protected routes Route::middleware(['web', 'auth:sanctum'])->group(function () { Route::get('v1/user/me', function (Request $request) { return response()->json([ 'user' => $request->user(), 'success' => true, ]); }); }); Frontend Auth Store (Nuxt.js) typescriptasync function login(email: string, password: string) { await getCsrfCookie(); // Gets CSRF token first

const response = await $fetch('/api/v1/user/login', { method: 'POST', body: { email, password }, credentials: 'include', // Important for cookies });

if (response.user) { user.value = response.user; } }

async function fetchUser() { const response = await $fetch('/api/v1/user/me', { method: 'GET', credentials: 'include', // This should send cookies but doesn't });

return response.user; }

// CSRF Cookie function export async function getCsrfCookie() { await $fetch('http://localhost:8000/sanctum/csrf-cookie', { credentials: 'include', }); } Login Method (Laravel) phppublic function login(Request $request) { $validated = $request->validate([ 'email' => 'required|email', 'password' => 'required|string', ]);

if (Auth::attempt($validated)) {
    $user = Auth::user();
    
    return response()->json([
        'success' => true,
        'user' => new UserResource($user),
        'debug' => [
            'auth_check' => Auth::check(),
            'user_id' => Auth::id(),
            'session_id' => session()->getId(),
        ]
    ]);
}

return response()->json(['success' => false], 401);

} What I've Tried

✅ Added credentials: "include" to all requests ✅ Set supports_credentials: true in CORS ✅ Used web middleware on all routes ✅ Set SESSION_DOMAIN=null ✅ Verified sessions table exists and working ✅ Added RouteServiceProvider with ['api', 'web'] middleware ✅ Tried different session drivers (file, database) ✅ Cleared all caches and cookies multiple times

Questions

Why are different session IDs being created for each request? Why aren't session cookies being sent with the /me request? Is there a configuration I'm missing for Nuxt.js + Laravel session sharing? Should I be using a different approach for SSR applications?

Environment

Laravel 11 Nuxt.js 3 (SSR enabled) PHP 8.2 MySQL 8.0 Chrome browser (tested in incognito)

Any help would be greatly appreciated! I've been stuck on this for days and can't figure out why the session cookies aren't being preserved between requests.

0 likes
4 replies
JussiMannisto's avatar

@abdul_rehman333 That's probably because you didn't bother formatting your message to make it readable. If you want free help, you should put in a bit of effort.

Accio's avatar

i am facing same problem now for days. in my case session keep changing because cookie not attach to localhost but only attach to DevTools->Application->Cookie->localhost:3000 which is wrong because its not sending the valid session to Laravel and thats why laravel keep generating new session. the fix answers i got are go live with under same domain to keep this cookie works like api.domain.com and domain.com or using session_driver = cookie bcs its ignoring the different session and keep generating new session s (which is bad even for development)

Would u tell me how you fix this problem for development? Please ignore the bad grammar :)

JussiMannisto's avatar

@Accio

in my case session keep changing because cookie not attach to localhost but only attach to DevTools->Application->Cookie->localhost:3000 which is wrong because its not sending the valid session to Laravel and thats why laravel keep generating new session

That makes no sense. Cookies don't care about ports, they only have a domain field.

I can't tell you what's wrong from this because I don't know how you've configured your app or what you're trying to do. You should read Sanctum's docs if you're having issues with it.

Please or to participate in this conversation.