#Deleting cookies in client components

1 messages · Page 1 of 1 (latest)

tough swallow
#

How to delete cookies in client components in next.js app router?

sturdy sealBOT
#

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:

  1. 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')
}
  1. 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', '')
}
  1. Using cookies().set(name, value, { maxAge: 0 }): This method sets the maxAge to 0, which will immediately expire a cookie.
'use server'
 
import { cookies } from 'next/headers'
 
async function delete(data) {
 cookies().set('name', 'value', { maxAge: 0 })
}
  1. Using cookies().set(name, value, { expires: timestamp }): This method sets the expires to 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 })
}
  1. Inside an API Route using the setHeader method 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:


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