#delete cookies

1 messages · Page 1 of 1 (latest)

umbral fable
#

I want to delete cookies but i got below error whenever i call remove cookie method to remove cookie. All my methods are server actions a given below. Please

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

Remove User Cookie server action

"use server";

import { cookies } from "next/headers";

export async function removeUserCookie(): Promise<void> {
    cookies().delete({
        name: "auth",
        path: "/",
    });
    cookies().delete({
        name: "user",
        path: "/",
    });
}

Function where cookie needs to be removed

"use server";

import { removeUserCookie } from "./logout";

export default async function validateSession(
    responseStatus: number,
): Promise<void> {
    if (responseStatus !== 200) {
        removeUserCookie()
        throw new Error(`Invalid Response: ${responseStatus}`);
    }
}

API Reference for the cookies function.

chrome lanternBOT
#

Hi @umbral fable. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, it seems like you're using the correct method to delete cookies in a server action. However, the error message you're seeing suggests that the code is not being executed in a server action or route handler context.

Here are a few things you could check:

  1. Make sure that the removeUserCookie function is being called within a server action or route handler. If it's being called from a client-side component or a function that's not a server action or route handler, you'll see the error message you're getting.

  2. Ensure that the removeUserCookie function is being imported correctly. If there's an issue with the import, the function might not be recognized as a server action.

  3. Check if the cookies().delete() method is being used correctly. According to the Next.js documentation (https://nextjs.org/docs/app/api-reference/functions/cookies#deleting-cookies), the delete method should be called with the name of the cookie as a string, like this:

cookies().delete('name')

In your code, you're passing an object to the delete method. Try changing your removeUserCookie function to this:

"use server";

import { cookies } from "next/headers";

export async function removeUserCookie(): Promise<void> {
    cookies().delete('auth');
    cookies().delete('user');
}

If you're still having issues after trying these steps, I would recommend opening a new issue in the Next.js GitHub repository (https://github.com/vercel/next.js/issues) with a detailed description of your problem and a minimal reproduction. The Next.js team or community members might be able to help you troubleshoot the issue.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: