astro/.changeset/thin-news-collect.md
Matthew Phillips d3091f89e9
Astro.cookies implementation (#4876)
* Astro.cookies implementation

* Remove unused var

* Fix build

* Add a changesetp

* Remove spoken-word expires
2022-09-28 16:55:27 -04:00

1.1 KiB

astro @astrojs/cloudflare @astrojs/deno @astrojs/netlify @astrojs/node @astrojs/vercel
minor minor minor minor minor minor

Adds the Astro.cookies API

Astro.cookies is a new API for manipulating cookies in Astro components and API routes.

In Astro components, the new Astro.cookies object is a map-like object that allows you to get, set, delete, and check for a cookie's existence (has):

---
type Prefs = {
  darkMode: boolean;
}

Astro.cookies.set<Prefs>('prefs', { darkMode: true }, {
  expires: '1 month'
});

const prefs = Astro.cookies.get<Prefs>('prefs').json();
---
<body data-theme={prefs.darkMode ? 'dark' : 'light'}>

Once you've set a cookie with Astro.cookies it will automatically be included in the outgoing response.

This API is also available with the same functionality in API routes:

export function post({ cookies }) {
  cookies.set('loggedIn', false);

  return new Response(null, {
    status: 302,
    headers: {
      Location: '/login'
    }
  });
}

See the RFC to learn more.