Astro Cookie Session

raw JSON →
1.3.0 verified Sat Apr 25 auth: no javascript

Middleware for managing session data using cookies in Astro SSR applications. Current version 1.3.0 (released 2024-12, active development). Session data is encrypted and stored client-side in cookies, not on the server, making it suitable for stateless architectures. Supports TypeScript with type-safe session definitions and optional flash messages. Key differentiators: zero external dependencies beyond Astro, encryption of payloads (added in 1.3.0), simple API similar to remix-run session handling, and built-in flash message support.

error Error: Encryption key not set. Please set SECRET_KEY_BASE environment variable.
cause Missing SECRET_KEY_BASE env variable or not loaded in Astro.
fix
Add SECRET_KEY_BASE to .env file and ensure Astro loads it (e.g., import 'dotenv/config' or use Astro's built-in env support).
error TypeError: Cannot destructure property 'getSession' of ... as it is undefined.
cause Attempting to import createCookieSessionStorage as default import.
fix
Use named import: import { createCookieSessionStorage } from 'astro-cookie-session'
breaking In v1.3.0, payloads are now encrypted by default. Existing sessions without encryption will fail to decrypt.
fix Regenerate all session data after upgrading to 1.3.0; old cookies are incompatible.
gotcha SECRET_KEY_BASE must be exactly 128 hex characters (openssl rand -hex 64 generates correct length). Using a key of different length will cause errors at runtime.
fix Generate key with: openssl rand -hex 64 and ensure no newline or extra characters.
gotcha Astro must be configured with output: 'server' (SSR mode). The middleware will not work in static export mode.
fix Set output: 'server' in astro.config.mjs.
gotcha The getSession function must be called with Astro.cookies (Astro 4+) or cookies (API routes). Using an incorrect argument will throw a runtime error.
fix Ensure you pass the correct cookies object: Astro.cookies in pages, or the cookies param in API routes.
npm install astro-cookie-session
yarn add astro-cookie-session
pnpm add astro-cookie-session

Setup SSR, create typed session storage, and use session in an Astro page to read/write encrypted cookies.

// .env
SECRET_KEY_BASE=$(openssl rand -hex 64)

// astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({ output: 'server' });

// src/sessions.ts
import { createCookieSessionStorage } from 'astro-cookie-session';
type SessionData = { userId: string };
export const { getSession } = createCookieSessionStorage<SessionData>();

// src/pages/index.astro
---
import { getSession } from '../sessions';
import type { APIRoute } from 'astro';

if (Astro.request.method === 'POST') {
  const form = await Astro.request.formData();
  const session = getSession(Astro.cookies);
  session.set('userId', form.get('id') as string);
}
const session = getSession(Astro.cookies);
const userId = session.get('userId');
---
{userId ? <p>Hello, {userId}!</p> : <form method="post"><input type="text" name="id"/><button>Log in</button></form>}