#Deleting cookies in client components
1 messages · Page 1 of 1 (latest)
Hi @tough swallow. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, you can only delete cookies in a Server Action or Route Handler. This is due to the fact that cookies are part of the HTTP protocol and can only be modified on the server side.
Here are some ways to delete cookies:
- Using
cookies().delete(name): This method explicitly deletes a cookie with a given name.
'use server'
import { cookies } from 'next/headers'
async function delete(data) {
cookies().delete('name')
}
- Using
cookies().set(name, ''): This method sets a new cookie with the same name and an empty value, effectively deleting the cookie.
'use server'
import { cookies } from 'next/headers'
async function delete(data) {
cookies().set('name', '')
}
- Using
cookies().set(name, value, { maxAge: 0 }): This method sets themaxAgeto 0, which will immediately expire a cookie.
'use server'
import { cookies } from 'next/headers'
async function delete(data) {
cookies().set('name', 'value', { maxAge: 0 })
}
- Using
cookies().set(name, value, { expires: timestamp }): This method sets theexpiresto any value in the past, which will immediately expire a cookie.
'use server'
import { cookies } from 'next/headers'
async function delete(data) {
const oneDay = 24 * 60 * 60 * 1000
cookies().set('name', 'value', { expires: Date.now() - oneDay })
}
- Inside an API Route using the
setHeadermethod on the response:
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.setHeader('Set-Cookie', 'username=; Path=/; HttpOnly; Max-Age=0')
res.status(200).send('Cookie has been deleted.')
}
Please note that you can only delete cookies that belong to the same domain from which .set() is called. Additionally, the code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete.
Sources:
- Next.js Docs - Deleting Cookies (https://nextjs.org/docs/app/api-reference/functions/cookies#deleting-cookies)
- Next.js Docs - Deleting Cookies in API Route Handlers (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#deleting-cookies)