Next.js Discord

Discord Forum

How to access request cookies on App Router API route

Answered
Turkish Angora posted this in #help-forum
Open in Discord
Turkish AngoraOP
Hey friends, wanting to know how to access cookies on a request in App Router API route

Currently, I have code that looks like this, where I'm checking the request for cookies... (pages router)

!req.cookies.refresh_token

I'd just like to replicate that functionality in my API route on the app router. Thanks!
Answered by Turkish Angora
I'm going to answer this thread myself and then close it out, I don't know if that is allowed or not but here goes.

Okay so to access the cookies coming in with an API request, you use the cookies method provided by next/headers
import {cookies} from "next/headers";

declare a new constant, on the Next Docs they call it cookie store
const cookieStore = cookies()

You can then access the cookies by using
cookieStore.get method

cookieStore.get('refresh_token'
returns the value of the refresh token.
View full answer

10 Replies

request.cookies
Turkish AngoraOP
I'm going to answer this thread myself and then close it out, I don't know if that is allowed or not but here goes.

Okay so to access the cookies coming in with an API request, you use the cookies method provided by next/headers
import {cookies} from "next/headers";

declare a new constant, on the Next Docs they call it cookie store
const cookieStore = cookies()

You can then access the cookies by using
cookieStore.get method

cookieStore.get('refresh_token'
returns the value of the refresh token.
Answer
@DirtyCajunRice | AppDir its in request.cookies.
yes, but you can't do request.cookies.refresh_token, you have to do request.cookies.get("refresh_token") – that is an important information that your answer lacked. in the original question the OP also used request.cookies.refresh_token but it didn't work.
@Turkish Angora you don't need cookies() here, you can use request.cookies which can be assigned to cookieStore above – the remaining steps become the same (cookieStore.get("something")?.value)
@Turkish Angora read title
you asked, i answered, joulev clarified my answer with the .get added to the request.cookies