#Deleting cookie using route handler

30 messages · Page 1 of 1 (latest)

jade jackal
#

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.

glad fableBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

jade jackal
#

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.

sour geode
#

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} },
})
}

sour geode
#

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

jade jackal
umbral sorrel
#

and like this to delete

export async function middleware(req: NextRequest) {
  const res = NextResponse.next();
  res.cookies.delete("cookie");
  return res;
}
jade jackal
#

Will try that

jade jackal
#

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

warped bough
#

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

umbral sorrel
jade jackal
#

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)

warped bough
sour geode
#

HomePage:
import Button from "@/components/logout/logout";
export default function Home() {

return (
<>
<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')
}

#

@jade jackal I hope this example help you

#

This example is not auth related it is only for setting and deleting cookie