Next.js Discord

Discord Forum

Unable to see cookies on server-side (app dir)

Answered
Bull Terrier posted this in #help-forum
Open in Discord
Bull TerrierOP
I am currently running this in my root layout.tsx:
export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
    const res = await fetch(`/auth/test`, {
          method: "GET",
          cache: "no-store",
          credentials: "include",
          headers: {
            "Content-Type": "application/json"
          }
    });

    return <></>
}

However, cookies are come back as undefined in my request in my server? I can however access them via the following:
const cookieStore = cookies();
const token = cookieStore.get("MY_COOKIE")?.value;

This is my separate Express Project (the middleware that I am utilising):
export default async (req: Request, res: Response, next: NextFunction) => {    
  console.log(req.cookies);
}

I am already using cookieParser();
I get the following returned: [Object: null prototype] {}
Answered by fuma
I see, so your code above has removed the url?

Again, doesn’t matter it is a fetch or an async function, you must use the [cookies](https://nextjs.org/docs/app/api-reference/functions/cookies) function provided by Next.js. The reason is that server components are rendered on server, by using the cookies function, you can receive the cookies from client.
View full answer

7 Replies

Barbary Lion
cookies are generally sent from the browser to the server. the fact that your nextjs server is making the call to the expressjs server, makes sense to me why you dont see those cookies in your express server.

if you want to do that, then you can look into "proxying" nextjs calls.

the most simplest thing though, would probably just pull the cookies in your nextjs code using cookies() and then passing them along into your new fetch() call to your express server.

ideally (i think) you'd just do what fuma said and call getData() directly as opposed to making a request to that server to do the same getData() call
@fuma **Don't** tsx const data = await fetch("/api/data"); **Do** tsx // directly get the data from server const data = await getData();
Bull TerrierOP
Can't get data directly from the server, backend is a separate Express Project
I see, so your code above has removed the url?

Again, doesn’t matter it is a fetch or an async function, you must use the [cookies](https://nextjs.org/docs/app/api-reference/functions/cookies) function provided by Next.js. The reason is that server components are rendered on server, by using the cookies function, you can receive the cookies from client.
Answer
Nice! Btw if your question has been solved, you can mark the answer as solution :yay: