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) {
cookies.delete('auth-redirect', { path: '/' })
const redirectUrl = cookieRedirect.value
return redirect(redirectUrl)
}
return redirect(`/${lang ?? 'en'}/app`)
}
if (user) {
return redirect(`/${lang ?? 'en'}/app`)
}
return redirect(`/${lang ?? 'en'}/${page}`)
}
The key changes are:
- Adding the
path option when deleting the cookie to ensure it matches how the cookie was set
- 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.