Open-Source Wikis

/

Astro

/

Features

/

Sessions

withastro/astro

Sessions

Per-user, server-side state with pluggable storage drivers. Configured in astro.config.mjs and accessed via Astro.session / context.session.

Purpose

Replace ad-hoc cookie/JWT patterns with a typed session object whose values are read/written server-side and stored anywhere (memory, Redis, libSQL, custom). The cookie that pairs the user with their data is signed and short.

Key files

File Purpose
packages/astro/src/core/session/runtime.ts The AstroSession runtime exposed on RenderContext.
packages/astro/src/core/session/drivers.ts Built-in drivers (memory + a unstorage-based factory).
packages/astro/src/core/session/config.ts Session config schema (driver, secret, cookie name, etc.).
packages/astro/src/core/session/types.ts SessionDriver, SessionDriverConfig, public types.
packages/astro/src/core/session/utils.ts Cookie signing, key handling.
packages/astro/src/core/session/vite-plugin.ts Vite plugin emitting the session virtual module.

Public types are re-exported from astro/types.

Configuration

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

export default defineConfig({
  session: {
    driver: 'redis',
    options: { url: process.env.REDIS_URL },
    cookie: { name: 'astro-session', sameSite: 'lax' },
  },
});

The driver value is resolved through unstorage, so any unstorage driver works (fs, redis, cloudflare-kv, vercel-kv, custom).

Runtime API

// Inside an .astro page, endpoint, action, or middleware
const userId = await Astro.session.get<string>('userId');
await Astro.session.set('userId', '42');
await Astro.session.regenerate();
await Astro.session.destroy();

Sessions are serialized as JSON and stored under a session ID derived from the signed cookie. The store is opened once per request.

How it works

graph LR
    A[Request] --> B[Read session cookie]
    B -->|signed| C{Valid?}
    C -- no --> D[New session id, lazy]
    C -- yes --> E[Load from driver]
    D --> F[Astro.session]
    E --> F
    F --> G[Page / endpoint / action]
    G --> H[Mutate session]
    H --> I[Persist via driver on response]
    I --> J[Set cookie if changed]
    J --> K[Response]

The session is loaded lazily — if your page never calls Astro.session.get, no driver call is made.

Encryption key

Signed cookies use the same runtime key as actions and server islands. Generate one with astro create-key and set process.env.ASTRO_KEY (the variable name comes from packages/astro/src/cli/create-key/).

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Sessions – Astro wiki | Factory