🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Server Rendering••By Komal Nakrani

Astro Cookies: Read, Set and Delete with Astro.cookies

Astro cookies explained: read, set and delete with Astro.cookies and context.cookies, secure options, JSON values, middleware, endpoints, Actions and common pitfalls.

#Astro#Astro Cookies#SSR#Middleware#Security

Astro cookies are handled through Astro.cookies in pages and components, and context.cookies in endpoints, middleware and Actions. Call cookies.get('name')?.value to read, cookies.set('name', value, options) to write, and cookies.delete('name', options) to remove a cookie. Cookies only work on routes rendered on demand, because a prerendered page is built once and has no visitor request to read from or response to write to.

This guide covers the full AstroCookies API, safe default options, where to set cookies so they actually reach the browser, and the mistakes that cause most cookie bugs.

Key Takeaways

  • Cookies need on-demand rendering: output: 'server' or export const prerender = false, plus an adapter.
  • get() returns an AstroCookie with .value, .json(), .number() and .boolean(), or undefined.
  • Always pass path: '/' when setting site-wide cookies; Astro does not add a default path.
  • Use httpOnly: true, secure: true and sameSite: 'lax' for session cookies.
  • Set cookies in the page frontmatter, middleware, endpoints or Actions, not in nested components after streaming starts.

Where cookies work in Astro

Cookies travel in HTTP headers: the browser sends them in the Cookie request header, and the server sets them with Set-Cookie response headers. In Astro, that only happens on routes rendered at request time.

Route type Can read cookies Can set cookies
Prerendered page (default in static output) No (build-time request has none) No
On-demand page (prerender = false) Yes Yes
On-demand API endpoint Yes Yes
Middleware on an on-demand route Yes Yes
Action Yes Yes

To make a page on-demand, add an adapter (Cloudflare, Netlify, Vercel or Node) and opt the route out of prerendering:

---
// src/pages/account.astro
export const prerender = false;
const theme = Astro.cookies.get('theme')?.value ?? 'light';
---
<html data-theme={theme}>
  <body><h1>Your account</h1></body>
</html>

The Astro SSR guide covers adapters and output modes in detail. On a fully static site, use client-side document.cookie or localStorage for preferences instead, since no server sees the request.

Reading cookies

get() returns an AstroCookie object, or undefined if the cookie is not present:

---
// src/pages/dashboard.astro
export const prerender = false;

const session = Astro.cookies.get('session')?.value;   // string | undefined
const visits = Astro.cookies.get('visits')?.number() ?? 0;
const banner = Astro.cookies.get('hideBanner')?.boolean() ?? false;
const prefs = Astro.cookies.get('prefs')?.json() as { lang?: string } | undefined;
---

The helper methods convert the raw string for you:

  • .value: the decoded string
  • .number(): parsed with Number()
  • .boolean(): true for "true", otherwise false
  • .json(): parsed with JSON.parse()

has('name') returns true if the cookie is in the request or was set earlier in the same request. Values are URL-decoded by default; pass { decode } as the second argument to get() if you encoded them differently.

Setting cookies

set() takes a name, a value and options:

// src/pages/api/preferences.ts
import type { APIRoute } from 'astro';

export const prerender = false;

export const POST: APIRoute = async ({ request, cookies, redirect }) => {
  const form = await request.formData();
  const theme = form.get('theme') === 'dark' ? 'dark' : 'light';

  cookies.set('theme', theme, {
    path: '/',
    maxAge: 60 * 60 * 24 * 365, // one year, in seconds
    sameSite: 'lax',
    secure: true,
  });

  return redirect('/account/', 303);
};

Strings are stored as is. Objects are serialized with JSON.stringify(), so you can store small structured values and read them back with .json():

cookies.set('prefs', { lang: 'en', units: 'metric' }, { path: '/', maxAge: 31_536_000 });

Keep cookie values small. Browsers limit each cookie to about 4 KB, and every cookie is sent with every request to your domain, so large cookies slow down every page load. Store an id in the cookie and keep the data on the server.

The options object accepts the standard Set-Cookie attributes:

Option What it does Recommended
path URL path the cookie is sent for '/' for site-wide cookies
domain Domain the cookie is sent to Leave unset unless sharing with subdomains
maxAge Lifetime in seconds Set for persistent cookies
expires Expiry as a Date Use maxAge instead, it is simpler
httpOnly Hide from document.cookie true for sessions and tokens
secure Only send over HTTPS true in production
sameSite 'strict', 'lax' or 'none' 'lax' for most cookies
partitioned CHIPS partitioned storage Only for third-party embeds
encode Custom value encoder Rarely needed

Two defaults surprise people. First, Astro does not add a default path, so a cookie set on /account/settings/ without path: '/' is only sent to /account/ URLs by the browser. Second, without maxAge or expires, a cookie is a session cookie and disappears when the browser closes.

For a login session, use all the protective options:

// src/lib/session.ts
import type { AstroCookies } from 'astro';

export function setSession(cookies: AstroCookies, id: string) {
  cookies.set('session', id, {
    path: '/',
    httpOnly: true,
    secure: import.meta.env.PROD,
    sameSite: 'lax',
    maxAge: 60 * 60 * 24 * 7,
  });
}

secure: import.meta.env.PROD keeps cookies working on http://localhost in development while forcing HTTPS in production.

Deleting cookies

delete() sends a Set-Cookie header with an expired date. It must use the same path and domain the cookie was set with, or the browser treats it as a different cookie and keeps the original:

// src/pages/api/logout.ts
import type { APIRoute } from 'astro';

export const prerender = false;

export const POST: APIRoute = ({ cookies, redirect }) => {
  cookies.delete('session', { path: '/' });
  return redirect('/', 303);
};

If a cookie “will not delete”, a mismatched path is almost always the reason.

Cookies in middleware

Middleware is the natural place to read a session cookie once and share the result with every page through locals:

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getUser } from './lib/auth';

export const onRequest = defineMiddleware(async (context, next) => {
  const id = context.cookies.get('session')?.value;
  context.locals.user = id ? await getUser(id) : null;

  if (context.url.pathname.startsWith('/account') && !context.locals.user) {
    return context.redirect('/login/');
  }
  return next();
});

Cookies set in middleware, before or after next(), are merged into the final response. The middleware guide and the Astro.locals guide cover the rest of this pattern.

Cookies in Actions

Actions receive the same context, so a form can set a cookie directly:

// src/actions/index.ts
import { defineAction } from 'astro:actions';
import { z } from 'astro/zod';

export const server = {
  dismissBanner: defineAction({
    accept: 'form',
    input: z.object({ id: z.string() }),
    handler: async ({ id }, context) => {
      context.cookies.set(`dismissed-${id}`, 'true', { path: '/', maxAge: 2_592_000 });
      return { ok: true };
    },
  }),
};

Common pitfalls

Setting a cookie in a nested component. Astro streams HTML. Once the page starts sending, headers are already on their way, and a set() call inside a deeply nested component is too late. Astro logs a warning that Astro.cookies.set() was called after the cookies had already been sent, or throws “Unable to set response.” Set cookies in the page’s frontmatter, in middleware, an endpoint or an Action.

Expecting cookies on prerendered pages. A page without prerender = false in static output was rendered at build time. Astro.cookies.get() returns undefined there, every time.

Reading a cookie you just set. This works within the same request: get() checks cookies set earlier in the request before reading the incoming header. The browser receives it with the response.

Missing path. Covered above, and the most common cause of “the cookie disappears on other pages”.

Storing secrets client-readable. Anything without httpOnly can be read by any script on the page. Session ids and tokens should always be httpOnly.

Consent. Cookies used for analytics or advertising generally need visitor consent in many regions. Functional cookies (sessions, preferences) usually do not, but check the rules that apply to you. The cookie consent banner guide shows a lightweight approach.

Sessions as an alternative

For server-side data tied to a visitor, Astro’s sessions API (Astro.session and context.session) stores data on the server with a storage driver and keeps only an id in a cookie. It saves you from managing the cookie yourself when you need more than a value or two. Sessions need an adapter with a configured storage driver.

Most marketing sites and blogs, including every Komal theme out of the box, are fully static and never touch server cookies. They become relevant when you add an account area, a gated download or saved preferences. For the official reference, see the Astro cookies API.

FAQ

Use Astro.cookies.get('name')?.value in a page or component, or context.cookies.get('name')?.value in an endpoint or middleware. The route must be rendered on demand, so add export const prerender = false and an adapter if your site is static by default.

Call Astro.cookies.set('name', 'value', { path: '/', maxAge: 3600 }) in a page’s frontmatter, or context.cookies.set() in an endpoint, middleware or Action. Include path: '/' for site-wide cookies and httpOnly, secure and sameSite for anything sensitive.

Why does Astro.cookies return undefined?

Usually because the page is prerendered, so there was no visitor request at build time. Add export const prerender = false and an adapter. Other causes are a cookie set with a narrower path, or a different domain than the one you are visiting.

Call cookies.delete('name', { path: '/' }) with the same path and domain used when the cookie was set. Astro sends an expired Set-Cookie header, and the browser removes the cookie.

Can I use cookies on a static Astro site?

Not on the server, because no server runs after the build. You can still read and write non-httpOnly cookies in the browser with document.cookie, or use localStorage for preferences. For server-side cookies, render the routes that need them on demand.