# Set custom cookie in the header and then redirect in Astro

> Learn how to set a cookie and redirect in Astro when Astro.redirect drops the Set-Cookie header, by returning a manual 302 Response with both headers set.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2023-12-13 | Topics: [Astro](https://flaviocopes.com/tags/astro/) | Canonical: https://flaviocopes.com/set-custom-cookie-in-the-header-and-then-redirect-in-astro/

I had the need to set a cookie and then redirect in [Astro](https://flaviocopes.com/astro-introduction/).

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()`:

```javascript
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:

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

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

![Source code showing Astro.redirect() creates a Response with status 302 and Location header](https://flaviocopes.com/images/set-custom-cookie-in-the-header-and-then-redirect-in-astro/1.webp)

…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:

```js
return new Response(null, {
  status: 302,
  headers: {
    Location: '/dashboard',
    'Set-Cookie': pb.authStore.exportToCookie({
      secure: import.meta.env.DEV ? false : true
    }),
  },
})
```
