Next.js Discord

Discord Forum

Deleting cookie using route handler

Unanswered
<Milind ツ /> posted this in #help-forum
Open in Discord
Hi, i have been trying to delete a cookie and have made a route handler for it. accessing cookiestore just returns empty cookie object/array. No value or anything

export async function POST(req: Request) {
   
   return await apiHandler(async () => {
      const { sessionCookie }: { sessionCookie: string } = await req.json();
      
      const cookieStore = cookies();
      console.log(cookieStore.size); // returns undefined

      // const cookie = cookieStore.get(sessionCookie);
      // console.log(cookie); // also returns undefined

      cookieStore.delete(sessionCookie); // does nothing
      console.log("deleted!");

      return NextResponse.json({
         status: 201,
         body: "Your session has been deleted!",
      });
   });
}


the controller that fetches the route
export const deleteCookie = async (sessionCookie: string) => {
   return await fetchHandler<string>(async () => {
      return await fetch(`${hostURL}/api/cookie`, {
         method: "POST",
         headers: {
            "Content-Type": "application/json",
         },
         body: JSON.stringify({
            sessionCookie: sessionCookie,
         }),
      });
   });
};


been trying to delete session cookie to handle one edge case.

29 Replies

kinda weird, according to docs, it says we need to use server actions or route handlers. In my case, i am using route handlers and only by wrapping it up by useeffect hook makes it work.
English Angora
Why you not accessing cookies directly in route handler?
You do not need to pass cookie from client to route handler instead directly delete cookie in route handler
import { cookies } from 'next/headers'

export async function GET(request: Request) {
const cookieStore = cookies()
const token = cookieStore.get('token')

return new Response('Hello, Next.js!', {
status: 200,
headers: { 'Set-Cookie': token=${token.value} },
})
}
English Angora
It is just a example i take from Nextjs docs
It is showing how to access cookie in route handler in same way you can delete cookie
@English Angora import { cookies } from 'next/headers' export async function GET(request: Request) { const cookieStore = cookies() const token = cookieStore.get('token') return new Response('Hello, Next.js!', { status: 200, headers: { 'Set-Cookie': `token=${token.value}` }, }) }
Yea I can make a route handler to get cookie but we still have to call it from somewhere. Wanted to do it from middleware but it doesn't work there. Any method of cookie() just returns empty array/object from middleware
@<Milind ツ /> Yea I can make a route handler to get cookie but we still have to call it from somewhere. Wanted to do it from middleware but it doesn't work there. Any method of cookie() just returns empty array/object from middleware
have you try reading the cookie like this in middleware?
export async function middleware(req: NextRequest) {
  const cookie = req.cookies.get("cookie")?.value
}
and like this to delete
export async function middleware(req: NextRequest) {
  const res = NextResponse.next();
  res.cookies.delete("cookie");
  return res;
}
Will try that
using next response to delete cookie just returns responseCookie as an object.
ResponseCookies {"next-auth.session-token":{"name":"next-auth.session-token","value":"","path":"/","expires":"1970-01-01T00:00:00.000Z"}}
using next request as req.cookies.delete() returns true atleast 5 times. no deletion whatsoever
Checkout open bug tickets maybe too
There used to be an actual bug in v12 early v13 that I noticed too a while back
it's probably fixed but tended to come back in other forms...
didn't test recently
you couldn't set 2 cookies too
@<Milind ツ /> using next request as req.cookies.delete() returns true atleast 5 times. no deletion whatsoever
could you show the code on how you delete the cookies? what do you mean by return true?
Say instead of using next response, we use the request from middleware arguments:

const data = req.cookies.delete(key)
So if we log the data, it shows true in console (not just 1 time but 5-10 times)
English Angora
HomePage:
import Button from "@/components/logout/logout";
export default function Home() {

return (
#Unknown Channel
<h1>This is Home Page</h1>
<Button>Logout</Button>
</>

);
}
Login Page:
import { loginHandler } from "../lib/actions"
export default function Login() {
return (
<form action={loginHandler}>
<label label="email">Email</label>
<input type="email" name="email"></input>
<button type="submit">Submit</button>
</form>
)
}
Button Component:
'use client'
import { logoutHandler } from "@/app/lib/actions"
const Button = ({children}) => {
const onLogout = async () => {
await logoutHandler()
}
return (
<button onClick={onLogout}>{children}</button>
)
}
export default Button
Server Actions:
'use server'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export const loginHandler = async (formData) => {
try {
const user = {
email: formData.get('email')
}

cookies().set({
name: 'test',
value: JSON.stringify(user),
httpOnly: true,
secure: true,
path: '/',
})

}
catch(err) {

}
redirect('/')
}
export const logoutHandler = async () => {
cookies().delete('test')
redirect('/login')
}
@<Milind ツ /> I hope this example help you
English Angora
This example is not auth related it is only for setting and deleting cookie
The example is already implemented using next auth. My use case is handling how to logout the user if the user gets deleted from backend for any reason. So the user will stay logged in. But I guess I could just use useEffect hook for this.