Next.js Discord

Discord Forum

Next 13 cant set cookie using route handlers

Unanswered
Philippine Crocodile posted this in #help-forum
Open in Discord
Philippine CrocodileOP
So I want to refresh the session for my users, for that I have created a route handler which basically calls my backend and refreshes the session. Now I have followed the docs of next and have done the excat same steps to modify the cookie but it is not being updated in the browser -> Application -> cookie tab. I have even logged cookies after request is completed but its still now showing up. Here is the Route handler code
import { cookies } from "next/headers";
import { NextResponse } from "next/server";

export async function GET(request: Request) {
  if (request.headers.get("cookie") === null)
    return NextResponse.json({
      isSuccess: false,
      message: "No token provided",
    });

  const response = await fetch("http://localhost:4000/refresh", {
    credentials: "include",
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      Cookie: request.headers.get("cookie") as string,
    },
  });

  const responseBody = await response.json();

  const newToken = responseBody.data.token;
  const tokenResponse = JSON.stringify({ newToken });

  return new Response(tokenResponse, {
    status: 200,
    headers: {
      "Set-Cookie": `accessToken=${newToken}; HttpOnly; Secure; SameSite=Strict; Path=/`,
    },
  });
}

Please help me with this as I have been stuck here for 2 days or suggest an alternative.

0 Replies