🔥 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 Sessions: Server-Side Session Storage Explained

Astro sessions explained: how Astro.session stores data on the server, which drivers adapters configure, typing SessionData, TTLs, security and when to turn sessions off.

#Astro#Astro Sessions#SSR#Server Rendering

Astro sessions let on-demand rendered routes store per-visitor data on the server and read it back on later requests, with only a session ID kept in a cookie. You use them through Astro.session in pages and context.session in middleware, endpoints and actions, and the data lives in a storage driver such as the filesystem, Redis or Cloudflare KV.

Sessions became stable in Astro 5.7 and are part of every Astro 7 project that uses an adapter. This article explains how they work, how to configure a driver, how to type your session data, and where sessions are the wrong tool.

Key Takeaways

  • Session data is stored server-side; the browser only gets an astro-session cookie holding the ID.
  • Sessions only work on routes rendered on demand. On prerendered pages Astro.session is undefined.
  • The Node, Cloudflare and Netlify adapters configure a default driver; otherwise set one with sessionDrivers in astro.config.mjs.
  • Declare App.SessionData to get typed get() and set() calls.
  • Since Astro 7.2 you can set session: false to drop the session runtime from the server bundle.

How Astro sessions work

A session is a small key-value store tied to one visitor. The first time you call Astro.session.set(), Astro generates a random session ID, saves your value in the configured storage driver under that ID, and sets a cookie on the response. On the next request the cookie comes back, Astro loads the stored values, and Astro.session.get() returns them.

That split matters for two reasons. The cookie never carries the data, so you can store things that are too large or too sensitive for a cookie, such as a cart, a multi-step form draft or a user record. And because storage is server-side, any server instance with access to the same driver sees the same session.

The default cookie settings are { name: "astro-session", sameSite: "lax", httpOnly: true, secure: true }, so client-side scripts cannot read the ID.

Sessions need a server at request time, which means an adapter and routes rendered on demand. If you have not set that up yet, our Astro SSR guide and adapters explained cover it.

Using Astro.session in a page

Here is a cart page that reads the session, plus a form that adds items. The page opts out of prerendering so it runs on every request:

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

if (Astro.request.method === 'POST') {
  const form = await Astro.request.formData();
  const sku = String(form.get('sku') ?? '');
  if (sku) {
    const cart = (await Astro.session?.get('cart')) ?? [];
    Astro.session?.set('cart', [...cart, sku]);
  }
  return Astro.redirect('/cart/', 303);
}

const cart = (await Astro.session?.get('cart')) ?? [];
---
<h1>Your cart</h1>
{cart.length === 0 ? <p>Your cart is empty.</p> : (
  <ul>{cart.map((sku) => <li>{sku}</li>)}</ul>
)}
<form method="POST">
  <input type="hidden" name="sku" value="mug-blue" />
  <button type="submit">Add a blue mug</button>
</form>

Note the shapes of the API: get(), has(), keys(), values() and entries() return promises because they may hit storage, while set(), delete() and destroy() are synchronous and are written when the response is sent. The optional chaining (Astro.session?.) is there because session is typed as possibly undefined, which is what you get on a prerendered page.

The session API at a glance

Method Returns What it does
get(key) Promise<value | undefined> Reads one value
set(key, value, { ttl }) void Writes a value; creates the session if needed
has(key) Promise<boolean> Checks whether a key exists
delete(key) void Removes one value
keys(), values(), entries() Promise<...> Lists stored data
regenerate() Promise<void> Issues a new session ID and keeps the data
destroy() void Clears the cookie and stored data
load(id) Promise<void> Replaces the current session with a stored one by ID
sessionID string | undefined The current ID

Values are serialised before storage, so stick to data that survives that: strings, numbers, booleans, arrays, plain objects and dates. Do not store class instances or functions.

Sessions in middleware, actions and endpoints

Anywhere you receive an APIContext, the session is on context.session. Middleware is a natural place to load the current user once and share it with every page through locals:

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

export const onRequest = defineMiddleware(async (context, next) => {
  if (context.isPrerendered) return next();

  const user = await context.session?.get('user');
  context.locals.user = user ?? null;

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

Inside an action, call context.session the same way. A login action should call regenerate() after a successful sign-in, so a session ID issued before login cannot be reused afterwards:

// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';
import { verifyPassword } from '../lib/auth';

export const server = {
  login: defineAction({
    accept: 'form',
    input: z.object({ email: z.email(), password: z.string().min(8) }),
    handler: async ({ email, password }, context) => {
      const user = await verifyPassword(email, password);
      if (!user) throw new ActionError({ code: 'UNAUTHORIZED', message: 'Wrong email or password' });
      await context.session?.regenerate();
      context.session?.set('user', { id: user.id, name: user.name });
      return { ok: true };
    },
  }),
};

See our guides to Astro middleware and Astro actions for the surrounding APIs.

Typing session data

Without types, get() returns any. Declare the shape once in src/env.d.ts and every call is typed:

// src/env.d.ts
declare namespace App {
  interface SessionData {
    user: { id: string; name: string };
    cart: string[];
    lastViewed: Date;
  }
  interface Locals {
    user: { id: string; name: string } | null;
  }
}

Now await Astro.session?.get('cart') is string[] | undefined, and set('cart', 42) is a type error.

Configuring a session driver

The Node, Cloudflare and Netlify adapters set up a default driver for you: the filesystem for Node, KV for Cloudflare and Netlify Blobs for Netlify. On other adapters, or when you want something different, pass a driver from sessionDrivers:

// astro.config.mjs
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 }),
    cookie: { name: 'shop-session', sameSite: 'lax' },
    ttl: 60 * 60 * 24 * 7,
  },
});

The drivers come from Unstorage, so the list is long: fs, redis, upstash, cloudflareKVBinding, netlifyBlobs, vercelKV, s3, mongodb, lruCache and more. Some need an extra package installed. Two details are easy to miss:

  • Driver options are inlined at build time. process.env.REDIS_URL above is read when you build, not when the server starts. To read credentials at runtime, the Astro sessions guide explains how to create your own driver entrypoint.
  • The old string form is deprecated. driver: 'redis' with a separate options object still works, but Astro now wants the function form shown above.

Expiry with ttl

session.ttl sets a default lifetime in seconds for every value, and set(key, value, { ttl }) overrides it per key. Expired values are removed lazily: the next read after expiry returns undefined and deletes the entry. If you need storage to clean itself up, use a driver that supports its own TTL.

Turning sessions off

If a project uses an adapter but never touches sessions, set session: false. Available since Astro 7.2, it removes the session runtime from the server bundle and tells adapters not to wire their default driver, which helps cold starts on serverless and edge hosts:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  session: false,
});

If storage cannot be reached, Astro throws SessionStorageInitError (“Session storage could not be initialized.”) or SessionStorageSaveError (“Session data could not be saved.”). Both usually mean a missing driver package, wrong credentials, or a driver that does not run on your host.

When not to use sessions

Sessions are for state the server needs. They are not the answer to everything:

  1. Static sites. A prerendered site has no server at request time. Use localStorage or a third-party service instead. Every Komal theme, for example, builds to static files, so sessions only come into play once you add an adapter yourself.
  2. Short UI preferences. A theme toggle or dismissed banner can live in a plain cookie or localStorage with no storage round trip.
  3. Authentication alone. Sessions are a building block. For OAuth, password resets and account management, an auth library that stores its sessions through Astro, or its own, saves a lot of work.

For the routing side of protected pages, our Astro routing guide shows where middleware fits, and the Astro config docs walk through the configuration file.

FAQ

Where does Astro store session data?

In the storage driver you configure, or the default your adapter provides: the filesystem with the Node adapter, KV on Cloudflare, Netlify Blobs on Netlify. The browser only holds a cookie containing the session ID.

Do Astro sessions work on static sites?

No. Sessions need code running at request time, so they only work on routes rendered on demand with an adapter. On prerendered pages Astro.session is undefined.

How do I log a user out with Astro sessions?

Call Astro.session.destroy() or context.session.destroy(). It clears the session cookie and deletes the stored data. To keep other data but drop the user, call delete('user') instead.

How long do Astro sessions last?

By default, stored values do not expire until they are deleted or the session is destroyed. Set session.ttl in seconds for a default lifetime, or pass { ttl } to set() for one key. The cookie itself can be configured through session.cookie.

What is the difference between Astro sessions and cookies?

Astro.cookies reads and writes cookies directly, so the data travels with every request and is limited in size. Sessions store data on the server and put only an ID in a cookie, which suits larger or more sensitive values.