I want to save tokens in cookies I got from the back-end.

(* I’m refactoring my previous side project. At the back-end, they didn’t put the token in Set-Cookie, but just gave it as a response body. I’m trying to figure out if there’s a way without fixing back-end code.)

So I made a request through the route handler as below code and saved it in the cookie.


import { SERVER_URL } from "@/constants/url";
import { NextRequest } from "next/server";
import { cookies } from "next/headers";

export async function GET(req: NextRequest) {
  const authCode = req.nextUrl.searchParams.get("code");
  const res = await fetch(`${SERVER_URL}/auth/login/kakao?code=${authCode}`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
  const data = await res.json();

  const at = data.data.accessToken;
  const response = Response.json({}, { status: 200 });

  cookies().set("accessToken", at);

  return response;

cookies().set("accessToken", at);


and the above code worked as I expected.

However, in page.tsx server component I can’t get cookie info.


async function getToken(authCode: string | string[]) {
  await fetch(`http://localhost:3000/api/token?code=${authCode}`, {
    method: "GET",

export default async function Page({ searchParams }: Props) {
  const { code } = searchParams;
  if (!code) redirect("/login");

  await getToken(code);

  const cookieStore = cookies();
  const cookieInfo = cookieStore.getAll();
  console.log("cookieInfo: ", cookieInfo);

  return <div>Saving Tokens</div>;

Am I totally wrong about cookies by any chance?

I can’t figure out what’s problem

I’ve tried using middleware or react-cookie, but they didn’t work as well.

return NextResponse.json(
    { headers: { 'Set-Cookie': `COOKIE_VALUE` } },

If the route handler returns as above, I don’t know how to access those values every time I send a request from my server component to the back-end API and put them in the header as authorization bearer.

And I wonder if there’s better way to manage my tokens(access, refresh) in front-end.

New contributor

윤석민 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.