How to Delete / Remove cookie
Unanswered
Cão Fila de São Miguel posted this in #help-forum
Cão Fila de São MiguelOP
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]: 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
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
3 Replies
Cão Fila de São MiguelOP
Login server action"use server";
import { APIResTypes, userAuthCookieType } from "@/types";
import { cookies } from "next/headers";
import { fetchUserProfileById } from "../getUserProfile";
export default async function userLogin(
username: string,
password: string,
): Promise<APIResTypes> {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_BASE_URL}/v1/login`,
{
method: "POST",
body: JSON.stringify({
username: username,
password: password,
}),
headers: {
"Content-Type": "application/json",
},
cache: "no-cache",
},
);
if (response.status !== 200 || !response.ok) {
const errorData = await response.json();
throw new Error(errorData.error.toString());
}
const data: userAuthCookieType = await response.json();
const userData: any = await fetchUserProfileById(
data.universalID,
data.sessionID,
);
if (!userData) {
throw new Error("No user data found");
}
cookies().set({
name: "auth",
value: JSON.stringify(data),
path: "/",
maxAge: 3600,
httpOnly: true,
});
cookies().set({
name: "user",
value: JSON.stringify(userData),
path: "/",
maxAge: 3600,
httpOnly: true,
});
return {
successMessage: "login successful!",
status: true,
};
} catch (error: any) {
return {
error: error.toString(),
status: false,
};
}
}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}`);
}
}