Read and Write Cookies With `Astro.cookies`
Cookies
`Astro.cookies` is the standard interface for reading and writing cookies in pages, endpoints, and middleware.
What you'll learn
- Read a cookie
- Set a cookie with options
- Delete a cookie
Astro.cookies is the standard interface for cookies in pages,
endpoints, and middleware. Works only in server-rendered contexts.
Reading
---
export const prerender = false;
const value = Astro.cookies.get("theme")?.value; // string | undefined
---
<p>Current theme: {value ?? "light"}</p> get(name) returns an AstroCookie | undefined with helpers like
.value, .json() (parse JSON), and .number().
Writing
---
Astro.cookies.set("theme", "dark", {
path: "/",
maxAge: 60 * 60 * 24 * 365, // 1 year
httpOnly: false, // accessible to JS
sameSite: "lax",
secure: import.meta.env.PROD,
});
--- The set call queues the cookie on the response. Astro writes the
Set-Cookie header automatically.
Deleting
Astro.cookies.delete("session", { path: "/" }); Storing JSON
Astro.cookies.set("prefs", JSON.stringify({ theme: "dark", lang: "en" }));
// later
const prefs = Astro.cookies.get("prefs")?.json(); // parses for you Sessions
For a heavier “session” pattern — signed, server-side state —
Astro ships Astro.session in newer versions, backed by a session
driver. Cookies remain the primitive underneath.
Security Notes
- For auth tokens:
httpOnly: true,secure: true,sameSite: "lax"(or"strict") - Sign or encrypt sensitive payloads — don’t put raw user data in a readable cookie
- Always set
path: "/"unless you really want to scope the cookie
Up Next
Environment variables — typed, validated.
Env Vars →