Sessions
By Syncfusion®, Inc. · Last updated
What sessions are, sessions vs cookies, session drivers and the adapter defaults, session.get() and set(), what you can store, regenerate() and destroy(), Astro.session and context.session, disabling sessions and typing App.SessionData.
Sessions
- A cookie is stored in the browser. The visitor can see it and change it.
- A session stores data on the server instead. The browser only keeps a random session ID in a cookie.
- On each request, Astro reads the ID and finds that visitor's data.
- In this lesson, you will store per-visitor data safely with
Astro.session.
Simple lesson: a session keeps a visitor's data on the server, linked by an ID cookie.
A Real-World Example
- Asha adds a "Recently viewed posts" box.
- The list belongs to one reader, and may grow long.
- In a cookie, the whole list would travel with every request, and the reader could edit it.
- In a session, the list stays on the server. The browser only holds a short ID.
Press ▶ Run. Open a few posts, then go back home. The Terminal shows the session being created.
What happened:
- The first
set()created a session. Astro sent a cookie calledastro-sessionwith a random ID. - Each post page added its slug to the list on the server.
- The home page read the list back with
get().
What You Will Learn
In this lesson, you will learn:
- What sessions are and how they differ from cookies.
- How session drivers store the data.
- How to read and write session data.
- What kinds of values you can store.
- How to change the ID with
regenerate()and end a session withdestroy(). - Where
Astro.sessionandcontext.sessionare available. - How to turn sessions off and add types.
What Sessions Are
Sessions vs Cookies
Animation: the browser keeps only a small session ID cookie. Each request carries the ID to the server, which looks up the visitor's data in its store.
Browser
astro-session=k7x2… only the ID
Server session store
k7x2… → recent: [3 posts] k7x2… → cart: 2 items p9q1… → (another visitor)
request carries the ID page built from the data
The browser holds the key. The server holds the box.
Use a cookie when:
- the data is small and not secret, such as a theme,
- browser JavaScript may need to read it.
Use a session when:
- the data is private, such as who is logged in,
- the data is large, such as a shopping cart,
- the visitor must not be able to change it.
Press ▶ Run, then click Again a few times. Both counters work, but read the Terminal: the cookie carries the number itself, the session cookie only carries an ID.
A Session Is Created on First Use
- Astro does not make a session for every visitor.
- It makes one the first time your code calls
set(). - Visitors who never need one never get a cookie.
Reading a session that does not exist yet is safe: get() just returns undefined. Only set() creates one.
Simple lesson: small, harmless data can be a cookie. Private or large data belongs in a session.
Configuring a Session Driver
What a Driver Is
- Session driver = where the server keeps session data: files, memory, Redis, a cloud store.
- The data must survive between requests, so the driver matters.
Default Drivers
- The Node adapter stores sessions in files on the server by default.
- The Cloudflare adapter uses Cloudflare KV. The Netlify adapter uses Netlify Blobs.
- With other adapters, such as Vercel, choose a driver yourself.
Choosing a Driver with sessionDrivers
import { defineConfig, sessionDrivers } from "astro/config";
import vercel from "@astrojs/vercel";
export default defineConfig({
adapter: vercel(),
session: {
driver: sessionDrivers.redis({ url: process.env.REDIS_URL }),
ttl: 60 * 60 * 24, // seconds until an unused session expires
},
});
ttl= "time to live": how long an unused session lasts.session.cookiechanges the cookie's name or options.
Configuring a Driver at Runtime (Advanced)
- Some drivers need values that only exist on the live server, such as a secret URL.
- Read them from environment variables when the server starts, not from code in the repository.
In this lab, sessions live in memory inside the preview and are lost when you press Run again. On a real server, the driver keeps them in files or a database.
Simple lesson: the adapter usually picks a driver for you. Choose one with sessionDrivers when it does not.
Reading and Writing
get() and set()
await Astro.session.get("key")returns the value, orundefined. It always needsawait.Astro.session.set("key", value)saves a value. Noawaitis needed.Astro.session.delete("key")removes one value.
What You Can Store
- Text, numbers,
true/false. - Arrays and plain objects.
Date,Map,SetandURLobjects. They come back as the same type.- Not functions or class instances with methods. Store their data instead.
Press ▶ Run. Add items to the cart. The cart is a Map in the session.
updatedAtcame back as a realDate, sotoLocaleTimeString()works.
Simple lesson: await get() to read, set() to write. Plain data, dates, maps and sets are all fine.
Changing and Ending Sessions
regenerate()
await Astro.session.regenerate()keeps the data but gives the session a new ID.- Call it when someone logs in. An attacker who knew the old ID can no longer use it.
- This protects against session fixation: tricking a visitor into using an ID the attacker chose.
destroy()
Astro.session.destroy()deletes the session data and the cookie.- Call it when someone logs out.
Using Sessions in Pages and Elsewhere
- In pages:
Astro.session. - In endpoints, actions and middleware:
context.session. - Only in on-demand routes. A static page is built before any visitor exists, so it has no session.
Press ▶ Run. Watch the session ID in the Terminal change when you press "Pretend to log in", and disappear on "Log out".
Sessions in Endpoints
- An endpoint reads the same session with
context.session.
Press ▶ Run. Add a sticker on the page, then click the link to the endpoint. It reads the same session.
Disabling Sessions
- Set
session: falseinastro.config.mjsto turn them off completely. - Then
Astro.sessionisundefined.
Sessions and Edge Middleware
- Some hosts run middleware on the edge: small servers close to the visitor.
- Edge middleware may not reach your session driver. Check your host's guide before using sessions there.
[TS] Typing App.SessionData
- Describe your session keys in
src/env.d.ts:
declare namespace App {
interface SessionData {
user: string;
cart: Map<string, number>;
recent: string[];
}
}
- Now
await Astro.session?.get("cart")is typed asMap<string, number> | undefined. - [JS] You do not need this. The values come back the same.
Always regenerate() the session after a login, and destroy() it on logout. Reusing the same ID across a login is a classic security hole.
Simple lesson: regenerate() on login, destroy() on logout. Sessions work only in on-demand routes.
TL;DR
- Session = per-visitor data on the server, linked by an
astro-sessionID cookie. - Cookie vs session = small public data in a cookie, private or large data in a session.
- Driver = where sessions are stored. Node, Cloudflare and Netlify adapters pick one. Others:
sessionDrivers. - Created on first use = the first
set()makes the session. - Read =
await session.get(key). Write =session.set(key, value). Remove =session.delete(key). - Values = text, numbers, arrays, objects,
Date,Map,Set,URL. - regenerate() = new ID, same data (on login). destroy() = all gone (on logout).
- Where =
Astro.sessionin pages,context.sessionelsewhere. On-demand only. - Off =
session: false.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
session.get() without await | It returns the value | await it | You get a Promise, not the value |
| Using a session on a static page | Every page has one | Use on-demand routes | Astro.session is undefined |
No regenerate() after login | The same ID is fine | Regenerate on login | Session fixation attacks |
| Storing a class instance | Any object works | Store plain data | Methods are lost |
Changing an object without set() | Changes save themselves | Call set() again after changing | The change is lost |
| No driver on a host without a default | Astro picks one | Configure session.driver | Sessions fail on the live site |
Check Yourself
Exercises
What to Remember
- A session keeps data on the server. The browser only holds the
astro-sessionID. - The adapter usually picks the storage driver. Choose one with
sessionDriverswhen needed. await get(),set(),delete(). Dates, maps, sets and plain data are kept.regenerate()on login,destroy()on logout.- Sessions only work in on-demand routes.
Next: Actions and Forms, where forms call type-safe server functions.