Skip to content

Set custom cookie in the header and then redirect in Astro

New Course Coming Soon:

Get Really Good at Git

I had the need to set a cookie and then redirect in Astro.

For some reason (using a library that wanted me to set a cookie string directly) I couldn’t use the Astro.cookies.set() API, which just works and you don’t need to worry about this.

Anyway I set the cookie using a response header using Astro.response.headers .append():

Astro.response.headers
  .append('Set-Cookie', 
    pb.authStore.exportToCookie())

Using return Astro.redirect('/') right after this didn’t work because the cookie was not attached to the redirect.

I used this instead:

return new Response(null, {
  status: 302,
  headers: {
    Location: '/dashboard',
    'Set-Cookie': pb.authStore.exportToCookie(),
  },
})

This is exactly what the Astro.redirect() does:

…except we set the Set-Cookie header too.

NOTE: for Safari compatibility on localhost (it doesn’t allow secure cookies on local), set the secure option as this:

return new Response(null, {
  status: 302,
  headers: {
    Location: '/dashboard',
    'Set-Cookie': pb.authStore.exportToCookie({
      secure: import.meta.env.DEV ? false : true
    }),
  },
})
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my Astro Tutorial on The Valley of Code

Here is how can I help you: