Next.js Discord

Discord Forum

cookies can only be modified in a server action or route handler next js" in the vercel logs

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Avatar
Northeast Congo LionOP
here is my singout action file code:
'use server'
import { revalidatePath } from "next/cache";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export const signout = async () => {
    cookies().delete("access_token");
    cookies().delete("refresh_token");
    cookies().delete("user");
    revalidatePath("/", "layout");
    redirect("/");
}


and here is my order action

"use server";
import axiosInstance from "@/components/axios";
import { signout } from "./signout_action";
import { returnCustomError } from "@/utilities/utils";

export const getOrders = async (pageNumber, query, filter) => {
    try {
        const res = await axiosInstance.get(
            `/api/reseller/orders/?page=${pageNumber}&search=${query}&status=${filter}`
        );
        return res?.data;
    } catch (error) {
        if (error.message === "Unauthorized") {
            signout();
        } else return [];
    }
};


now when user is unauthorized it run singout funtin and clear cookies in development mode and go to home page but ini the production it gives an error "cookies can only be modified in a server action or route handler next js" in the vercel logs

and show application error: a client side exceptions occured (see browser console)

this type of error shows on the screen

how to solve this in next js 14 app router

8 Replies

Avatar
Barbary Lion
what happens if you await?

if (error.message === "Unauthorized") {
  await signout();
} else return [];
import { cookies } from "next/headers";
// ...
export const signout = async () => {
  const cookieStore = await cookies()
  cookieStore.delete("access_token")
  // ...
}
You should await cookies first, and save that to a variable to use again
Avatar
@Pinea You should await cookies first, and save that to a variable to use again
Avatar
Asian black bear
This is not true for Next 14, only 15.
Avatar
@Asian black bear This is not true for Next 14, only 15.
Avatar
Oh really? Had no idea sorry
Avatar
Asian black bear
The dynamic functions such as headers and cookies have been made async in Next 15, but have been synchronous previously.
Avatar
Makes sense, I've only started properly using next.js since next 15 so