Next.js Discord

Discord Forum

Accessing cookies on server. Sending them with fetch...am i doing it right?

Answered
johan liebert posted this in #help-forum
Open in Discord
Im new to nextjs and trying to build a gpt-clone. After reading the docs, i can able to get the cookies from browser to my server side with cookies() and also able to send a request to external server too. My doubt is am i doing it correctly with fetch request? (cause it looks so naive) or is there any better approach?

"use server";

import { cookies } from "next/headers";

export async function getAllChats() {
  const cookieStore = cookies();
  const token = cookieStore.get("gpt-token");

  const response = await fetch("http://localhost:5000/chats", {
    method: "GET",
    credentials: "include",
    headers: {
      Cookie: `gpt-token=${token?.value}`,
    },
  });

  const result = await response.json();
  return result.chats;
}
Answered by Rafael Almeida
yeah this is perfectly fine
View full answer

3 Replies