Cookie not available in middleware after login.
Answered
Barbary Lion posted this in #help-forum
Barbary LionOP
I've managed to replicate the initial issue I encountered. Here's what's happening: within the middleware, I attempt to retrieve the session. If the user lacks a session, I redirect them to the login page. Once they log in and the cookie is set, the middleware is triggered automatically. However, despite setting the cookie, I'm still unable to access the session. I find that I need to reload the page in order to finally access the cookie through the request.
Answered by Ray
try this
if (req.method !== 'POST') {
console.log(req.cookies);
const session = await getSession();
console.log(session);
}11 Replies
@Ray could you show your middleware?
Barbary LionOP
Sure,
the auth.ts file:
import { NextRequest, NextResponse } from "next/server";
import { getSession } from "./auth";
export async function middleware(req: NextRequest) {
console.log(req.cookies);
const session = await getSession();
console.log(session);
return NextResponse.next();
}
export const config = {
matcher: [
/**
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - uploads (uploaded files)
* - favicon.ico (favicon file)
* - robots.txt (robots file)
*/
"/((?!api|_next/static|_next/image|uploads|favicon.ico|robots.txt).*)"
]
};the auth.ts file:
"use server";
import { cookies } from "next/headers";
import { randomUUID } from "crypto";
export async function getSession() {
const session = cookies().get("ssid")?.value;
return session?.length ? session : null;
}
export async function login() {
cookies().set("ssid", randomUUID(), {
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),
httpOnly: true,
sameSite: "lax",
path: "/"
});
}
export async function logout() {
cookies().delete("ssid");
}Answer
the server action will hit the middleware too
@Ray try this
ts
if (req.method !== 'POST') {
console.log(req.cookies);
const session = await getSession();
console.log(session);
}
Barbary LionOP
Holy shit man.... It just works.. 😂 You can't imagine how long I was trying to solve that 💀
@Ray nice
Barbary LionOP
Can I also set a cookie from an API route? If I want to handle the login for example using the API.
@Barbary Lion Can I also set a cookie from an API route? If I want to handle the login for example using the API.
Yes you can but you would need to clear the router cache with router.refresh
Server action does it for you
@Ray Yes you can but you would need to clear the router cache with router.refresh
Barbary LionOP
Okay, so there is not really a reason to use API.
@Ray Yes you can but you would need to clear the router cache with router.refresh
Barbary LionOP
Okay, but I guess in my case I need to do that, as I cannot use the Crypto module inside the middleware. I need that to decrypt the cookie.