Next.js Discord

Discord Forum

apply the set-cookie header from a response on fetch request made in server action

Unanswered
Bluethroat posted this in #help-forum
Open in Discord
BluethroatOP
Hi, I use a server action to fetch user data on an external api which handles authentication. The external api sends a set-cookie header to refresh the backend session. If I use route handlers to fetch the data and return a response, the session cookie is updated on the browser. But, the problem is that if I use server actions... I don't know how to manually get that set-cookie header and apply it. Can anybody help my with this?

3 Replies

BluethroatOP
Noone??
"use server";

import { cookies } from "next/headers";

export async function create() {
  const cookieStore = cookies();

  const currentTheme = cookieStore.has("theme") ? cookieStore.get("theme").value : "dark";
  const newTheme = currentTheme === "dark" ? "light" : "dark";
  
  await cookieStore.set({
    name: "theme",
    path: "/",
    value: newTheme,
  });
}
@Bluethroat check if it works