Next.js Discord

Discord Forum

Accessing Cookies From Middleware (middleware.ts)

Answered
Poyraz Hancılar posted this in #help-forum
Open in Discord
Hello everyone, I'm trying to make Middleware for Authentication. And I must check & set cookie variables from middleware. But when I try to use cookie thing in (https://nextjs.org/docs/app/api-reference/functions/cookies) this document, I got an error like this:
Answered by Sloth bear
You can get cookies like this in middleware:

const cookie = request.cookies.get("some-cookie");

// to set cookies,
 const response = NextResponse.next();
response.cookies.set({
   name: "mycookie",
   value: "hello",
   path: "/",
});
View full answer

5 Replies

can you perhaps, get cookies from the request object?
I tried that but it seems I can't do it correctly. Is there any docs to you refer?
I tried this
Sloth bear
You can get cookies like this in middleware:

const cookie = request.cookies.get("some-cookie");

// to set cookies,
 const response = NextResponse.next();
response.cookies.set({
   name: "mycookie",
   value: "hello",
   path: "/",
});
Answer