#How do I properly delete HTTPOnly cookie in app router?
1 messages · Page 1 of 1 (latest)
Hi @wintry ember. 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 delete cookies in a Server Action or Route Handler. There are several ways to delete a cookie:
- You can explicitly delete a cookie with a given name using
cookies().delete(name). Here's an example:
'use server'
import { cookies } from 'next/headers'
async function create(data) {
cookies().delete('name')
}
(Source: Next.js Docs - Functions - Cookies (https://nextjs.org/docs/app/api-reference/functions/cookies))
- Alternatively, you can set a new cookie with the same name and an empty value using
cookies().set(name, ''). Here's an example:
'use server'
import { cookies } from 'next/headers'
async function create(data) {
cookies().set('name', '')
}
(Source: Next.js Docs - Functions - Cookies (https://nextjs.org/docs/app/api-reference/functions/cookies))
- You can also set
maxAgeto 0 to immediately expire a cookie usingcookies().set(name, value, { maxAge: 0 }). Here's an example:
'use server'
import { cookies } from 'next/headers'
async function create(data) {
cookies().set('name', 'value', { maxAge: 0 })
}
(Source: Next.js Docs - Functions - Cookies (https://nextjs.org/docs/app/api-reference/functions/cookies))
Remember, these methods are only available in a Server Action or Route Handler. If you're seeing an issue with these methods, it's recommended to open a new issue with a reproduction so the Next.js team can investigate your case.
(Source: Github Issue - Docs: Setting cookies in API Route Handlers isn't working at all (https://github.com/vercel/next.js/issues/52799))
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@wintry ember kapa.ai is still learning and improving, please let us know how it did by reacting below
@quasi mirage How do I redirect the user after deleting the cookie?
Let me check the knowledge base for you. One moment! :books:
After deleting the cookie, you can redirect the user by using the NextResponse.redirect() method. Here's an example:
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.')
return NextResponse.redirect('/your-redirect-url')
}
In this example, after the cookie is deleted, the user is redirected to '/your-redirect-url'. You can replace '/your-redirect-url' with the actual URL where you want to redirect the user.
Please note that the NextResponse.redirect() method is available in Next.js 12 and later versions.