I’m building an app where my backend is a Laravel API (running on http://localhost:8000) and my frontend is a Next.js 15 app (running on http://localhost:3000).
I want to store the Sanctum token inside an HttpOnly cookie (for XSS/CSRF protection) so when the user logs in via the Laravel API, the cookie will automatically included in requests from both:
Next.js Server Components
Next.js Client Components
What I tried
On the Laravel side, I issued the token and attached it to a cookie:
$cookie = cookie('auth_token', $token, 60, '/', null, true, true, false, 'lax');
return response()->json([
'status' => 'success',
'token' => $token,
'user' => $user->only('id', 'name', 'email', 'phone'),
])->cookie($cookie);
On the Next.js side, I tried two approaches:
1. Rely on Laravel’s cookie
The cookie is created correctly, but it isn’t accessible from my Next.js app since it’s set on a different origin (localhost:8000 vs localhost:3000).
2. Manually set a cookie in Next.js server action
cookieStore.set("auth_token", json.token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
});
- This works for server-side requests when I manually add the Bearer token.
- But for client-side requests, I can’t access the HttpOnly cookie in JavaScript (by design).
Question
How can I properly share the HttpOnly authentication cookie between Laravel (localhost:8000) and Next.js (localhost:3000) so that:
- The cookie is set once in Laravel after login
- It is automatically sent with requests from both Next.js server and client components
- Without exposing the token to JavaScript (still HttpOnly)
Do I need to configure a shared domain (e.g. .myapp.test) instead of localhost for this to work, or is there another recommended way?