How do I get client cookies in API route or Middleware?
Answered
Mugimaki Flycatcher posted this in #help-forum
Mugimaki FlycatcherOP
Basically I want to update expiration date so I need to get session token from cookies. Works on server actions but I can't get value in middleware or API routes even if I call server action inside.
15 Replies
Mugimaki FlycatcherOP
14.1.3
also tried setting as httpOnly cookie
cookies().set("session", session.token, {
expires: expirationDate,
httpOnly: true,
});@Mugimaki Flycatcher 14.1.3
I have no problem to get client cookie with 14.1.4, maybe you could try that?
Mugimaki FlycatcherOP
upgraded still same happened but found out that i get cookies in middleware but not in api route 😕
not sure if upgrading had effect on middleware getting cookies
api route
not sure if upgrading had effect on middleware getting cookies
await fetch("http://localhost:3000/api/update-session");
console.log(request.cookies.getAll());api route
export const dynamic = "force-dynamic";
export async function GET(request: NextRequest) {
const sessionToken = cookies().get("session")?.value;
const sessionToken2 = request.cookies.get("session")?.value;
console.log({ sessionToken });
console.log({ sessionToken2 });
const sessionTokenFromServerAction = await getToken();
console.log({ sessionTokenFromServerAction });rename middleware.ts to _middleware.ts
Mugimaki FlycatcherOP
same thing happening
As a workaround I could do post method or call server action in a middleware 😄
@Mugimaki Flycatcher same thing happening
ah you are fetching the api on the page,
try go to http://localhost:3000/api/update-session on your browser
Mugimaki FlycatcherOP
works in console ðŸ‘ðŸ¾
if you make the request on the page, the request is made from server which doesn't have the cookies information
@Mugimaki Flycatcher As a workaround I could do post method or call server action in a middleware 😄
Mugimaki FlycatcherOP
What about middleware? should I go for workaround?
@Mugimaki Flycatcher What about middleware? should I go for workaround?
I think its better to do that in middleware
Answer