Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to delete cookie using Next.js server side action

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

like image 924
hantoren Avatar asked Mar 01 '26 03:03

hantoren


1 Answers

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

like image 192
Igor Danchenko Avatar answered Mar 03 '26 15:03

Igor Danchenko