#bug when deleting cookies

4 messages · Page 1 of 1 (latest)

noble sand
#

import type { APIRoute } from 'astro'

export const GET: APIRoute = async ({ params, locals, redirect, cookies }) => {
const { page, lang } = params
const user = locals.user

if (page === 'redirect' && user) {
    const cookieRedirect = cookies.get('auth-redirect')
    if (cookieRedirect) {
        cookies.delete('auth-redirect')
        return redirect(cookieRedirect.value)
    }
    return redirect(`/${lang ?? 'en'}/app`)
}

if (user) {
    return redirect(`/${lang ?? 'en'}/app`)
}

return redirect(`/${lang ?? 'en'}/${page}`)

}

export const prerender = false
in this code why the cookies is not getting deleted in the case where page === 'redirect' and the cookie exist ?

reef oakBOT
#

Hi @noble sand. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The issue you're experiencing with cookies not being deleted is likely related to how Astro handles response headers and redirects. When you call redirect() immediately after deleting a cookie, the cookie deletion might not be properly applied because the response is already being sent.

In Astro, when you return a redirect, it creates a Response object that gets sent immediately. This means any modifications to cookies or headers need to be fully processed before the redirect happens.

Here's how you can fix this issue:

export const GET: APIRoute = async ({ params, locals, redirect, cookies }) => {
    const { page, lang } = params
    const user = locals.user

    if (page === 'redirect' && user) {
        const cookieRedirect = cookies.get('auth-redirect')
        if (cookieRedirect) {
            // Delete the cookie
            cookies.delete('auth-redirect', { path: '/' })
            
            // Store the redirect URL
            const redirectUrl = cookieRedirect.value
            
            // Return the redirect response
            return redirect(redirectUrl)
        }
        return redirect(`/${lang ?? 'en'}/app`)
    }

    if (user) {
        return redirect(`/${lang ?? 'en'}/app`)
    }

    return redirect(`/${lang ?? 'en'}/${page}`)
}

The key changes are:

  1. Adding the path option when deleting the cookie to ensure it matches how the cookie was set
  2. Storing the redirect URL in a variable before redirecting

This issue is related to how Astro handles responses. As mentioned in the documentation, once a response has been sent to the browser, it cannot be altered. When you call redirect(), it creates and sends a Response, so any cookie modifications need to be fully processed before that happens.