Next.js Discord

Discord Forum

fetching api route cant access cookie

Answered
Gharial posted this in #help-forum
Open in Discord
GharialOP
So this is the context, my server page fetch data from my api route which uses cookie and the api route cant seem able to get the cookie. I wonder why?
Answered by joulev
you need to use headers() or cookies() to grab the cookie from the request from the browser, then attach that cookie to the request that you make from the server
View full answer

13 Replies

@Gharial So this is the context, my server page fetch data from my api route which uses cookie and the api route cant seem able to get the cookie. I wonder why?
because the server doesn't have any cookie. the browser has the cookie.

you need to use [headers()](https://nextjs.org/docs/app/api-reference/functions/headers) or [cookies()](https://nextjs.org/docs/app/api-reference/functions/cookies) to grab the cookie from the request from the browser, then attach that cookie to the request that you make from the server
@Gharial I mean if i use cookie directly from the server page it works?
what do you mean by "cookie directly from the server page"?
GharialOP
this works
// /app/page.tsx
import { cookies } from 'next/headers'

export default function Home() {
  const token = cookies().get('token')?.value
}

this works
// /api/cookie/route.ts
import { cookies } from 'next/headers'

export default function  GET() {
  const token = cookies().get('token')?.value
  return NextResponse.json(token)
}


but this doesnt
export default function Home() {
  const token = await fetch(.../cookie)....
  // we wont be able to get token this way
}
why is that?
GharialOP
how should I handle this?
pass the token from the pages to the api? any other good way?
you need to use headers() or cookies() to grab the cookie from the request from the browser, then attach that cookie to the request that you make from the server
Answer
like this
import { cookies } from "next/headers";

async function getData() {
  const response = await fetch(process.env.API_ENDPOINT, {
    headers: { Cookie: cookies().toString() },
  });
  return await response.json();
}
GharialOP
nice! Thanks!