Next.js Discord

Discord Forum

How to delete cookie from middleware?

Answered
European pilchard posted this in #help-forum
Open in Discord
Avatar
European pilchardOP
I'm checking the expiry time of token in middleware and if the expiry time is less than 'now' time I want to delete the cookie.
From next js documentation I came to know that we can only delete cookies from route handler or server so I made a API route '/api/auth/logout ' where I delete the cookie, the API is being called as expected but cookie is not deleted . can anyone please provide insight to this problem?
Answered by B33fb0n3
hm... then do it like this:
  const response = NextResponse.next();
  response.cookies.delete("test"); // exchange the key
  return response;
View full answer

24 Replies

Avatar
there is no need for an extra route handler, that handles the deletion of the cookie. You can easily delete the cookie inside the middleware though the request:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
export function middleware(request: NextRequest) {
  // Assume a "Cookie:nextjs=fast" header to be present on the incoming request
  // Getting cookies from the request using the `RequestCookies` API
  let cookie = request.cookies.get('nextjs')
  console.log(cookie) // => { name: 'nextjs', value: 'fast', Path: '/' }
  const allCookies = request.cookies.getAll()
  console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }]
 
  request.cookies.has('nextjs') // => true
  request.cookies.delete('nextjs')
  request.cookies.has('nextjs') // => false
 
  // Setting cookies on the response using the `ResponseCookies` API
  const response = NextResponse.next()
  response.cookies.set('vercel', 'fast')
  response.cookies.set({
    name: 'vercel',
    value: 'fast',
    path: '/',
  })
  cookie = response.cookies.get('vercel')
  console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' }
  // The outgoing response will have a `Set-Cookie:vercel=fast;path=/` header.
 
  return response
}
Avatar
European pilchardOP
thanks will try this.
Avatar
when will you try it?
Avatar
European pilchardOP
now.I was having lunch just finished.
If it works you're the GOD.
Avatar
European pilchardOP
export async function middleware(request: NextRequest) {
  const allCookies = request.cookies.getAll();
  const hasCookies = request.cookies.has("token");
  logger.log("I have cookie", hasCookies) ;
  request.cookies.delete("token");
}

it should be enough right?
it's not working.
Avatar
can you clarify what's specifically not working?
Avatar
European pilchardOP
it's not deleting the cookie man.
Avatar
you also need to return a specific response (new response) with the deleted cookie
Avatar
European pilchardOP
somthing like this?
  const response = NextResponse.next();
  request.cookies.delete("token");
  return response;
Avatar
do it like this:
Green box: check if there is a cookie and delete it (you can also directly check if it's gone)
Orange box: Create the new response
Blue box: check if the cookie is now gone
Yellow box: return the response
Image
Avatar
European pilchardOP
ok trying now.
Avatar
European pilchardOP
export async function middleware(request: NextRequest) {
  console.log(request.cookies.has("token")); //-->returning true
  request.cookies.delete("token");
  console.log(request.cookies.has("token")); //-->returning false
  const response = NextResponse.next();
  return response;
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"]
};
but the actual cookie is not deleted in browser.
am i missing something?
Avatar
can you confirm, that the blue box returns the value as null?
Avatar
European pilchardOP
it's undefined.
Avatar
hm... then do it like this:
  const response = NextResponse.next();
  response.cookies.delete("test"); // exchange the key
  return response;
Answer
Avatar
European pilchardOP
it actually worked but somethimes it doesn't work
Avatar
It works perfectly. You can see an example here: https://zg97gh-3000.csb.app/
And the code for it here:
https://codesandbox.io/p/devbox/zg97gh
Avatar
European pilchardOP
yeah it works.thanks man. actually my middleware is more than just that consisting multiple redirects and fairly complex logic .I think problem is in my logic part not in next js . thanks again.
Avatar
ah ok, happy to help