I'm trying to delete a cookie using the next/headers module in a Next.js application, but it doesn't seem to work as expected. Here's the code snippet:
import {cookies} from "next/headers";
export default async function Signout() {
async function deleteTokens() {
"use server"
cookies().delete('accessToken')
}
await deleteTokens()
return (
<></>
);
}
I expected the cookies().delete('accessToken') line to delete the cookie named "accessToken", but it doesn't seem to have any effect. The cookie is still present after the function is executed.
I am getting following error: Error: 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
But i have set the "use server" and enabled it in the next.config.js
#using Next.js 13.4.4
The issue here is that your function runs as part of the server component, not as a server action. You can execute your function as a server action by passing it down to a client component and calling it from a client component on page load.
// app/signout/page.js
import { cookies } from "next/headers";
import SignOutAction from "./SignOutAction";
export default async function SignOut() {
async function deleteTokens() {
"use server";
cookies().delete("accessToken");
}
return <SignOutAction deleteTokens={deleteTokens} />;
}
// app/signout/SignOutAction.js
"use client";
import { useEffect, useRef } from "react";
export default function SignOutAction({ deleteTokens }) {
const deleteTokensRef = useRef(deleteTokens);
useEffect(() => {
deleteTokensRef.current = deleteTokens;
});
useEffect(() => {
deleteTokensRef.current();
}, []);
return null;
}
P.S. This is not directly related to your original question, but this implementation is prone to CSRF vulnerability - https://security.stackexchange.com/questions/62769/should-login-and-logout-action-have-csrf-protection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With