Sessions & Middleware in Astro

From the Astro cheat sheet ยท Modern Astro (Server Islands, Actions, Sessions) ยท verified Jul 2026

Sessions & Middleware

Built-in sessions (5.1+) and the middleware request/response chain

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

export const onRequest = defineMiddleware(async (context, next) => {
  // Read or write per-request session data
  const cart = await context.session?.get('cart') ?? []
  context.locals.cart = cart

  const res = await next()
  return res
})

// astro.config.mjs: sessions are stable in Astro 6+ (no experimental flag)
import { defineConfig, sessionDrivers } from 'astro/config'
export default defineConfig({
  session: {
    driver: sessionDrivers.redis({ url: process.env.REDIS_URL }),
  },
})
๐Ÿ’ก Middleware runs on every request โ€” set locals there, read in pages
โšก sequence() composes multiple middlewares cleanly in render order
๐Ÿ“Œ Sessions are stable in Astro 6+ (no experimental flag); set driver via sessionDrivers, or let the Node/Netlify/Cloudflare adapter auto-configure one
๐ŸŽฏ Always declare App.Locals and App.SessionData in env.d.ts for full type safety
middlewaresessionsauth

Continue with Astro

Save the full cheat sheet or work through every related task.

More Astro tasks

Back to the full Astro cheat sheet