how can modify cookies in route handler with server action

let say we have page route
export defualt function Page(){
const user=await getUser();
if(!user){
/*
serversignout is server action which implements a another page
*/
serversignout();
redirect("/login");
}
return <div>my page</div>
}
export defualt function Page(){
const user=await getUser();
if(!user){
/*
serversignout is server action which implements a another page
*/
serversignout();
redirect("/login");
}
return <div>my page</div>
}
server signout is implemented as given below
"use server"
//necessary imports
export async function serversignout() {
const cookiesStore = cookies();
const csrf = cookiesStore.get("next-auth.csrf-token");
cookies().set({
name: "next-auth.csrf-token",
value: "",
expires: new Date("2016-10-05"),
path: "/", // For all paths
});
cookies().set({
name: "next-auth.callback-url",
value: "",
expires: new Date("2016-10-05"),
path: "/", // For all paths
});
cookies().set({
name: "next-auth.session-token",
value: "",
expires: new Date("2016-10-05"),
path: "/", // For all paths
});

console.log(csrf);
await fetch(absoluteUrl("/api/auth/signout"), {
cache: "no-cache",
method: "POST",
body: JSON.stringify({ csrfToken: csrf?.value }),
});
}
"use server"
//necessary imports
export async function serversignout() {
const cookiesStore = cookies();
const csrf = cookiesStore.get("next-auth.csrf-token");
cookies().set({
name: "next-auth.csrf-token",
value: "",
expires: new Date("2016-10-05"),
path: "/", // For all paths
});
cookies().set({
name: "next-auth.callback-url",
value: "",
expires: new Date("2016-10-05"),
path: "/", // For all paths
});
cookies().set({
name: "next-auth.session-token",
value: "",
expires: new Date("2016-10-05"),
path: "/", // For all paths
});

console.log(csrf);
await fetch(absoluteUrl("/api/auth/signout"), {
cache: "no-cache",
method: "POST",
body: JSON.stringify({ csrfToken: csrf?.value }),
});
}
can anyone tell me why it is giving error in production as ReadonlyRequestCookiesError: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options please help
Functions: cookies
API Reference for the cookies function.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server