Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท SSR, Adapters and Endpoints

Astro Middleware, Cookies and Authentication

Write Astro middleware with defineMiddleware and sequence, share data through locals, set secure cookies and protect routes with a session check.

Some work must happen for many routes: checking login, adding security headers, logging, redirecting old paths, picking a language. Copying that code into every page is error-prone. Astro's middleware runs before a page or endpoint, can read and change the request context, and can short-circuit with its own response.

The middleware file

Create src/middleware.ts (or src/middleware/index.ts). Export an onRequest function:

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

export const onRequest = defineMiddleware(async (context, next) => {
  const started = performance.now();

  const response = await next();

  const ms = Math.round(performance.now() - started);
  response.headers.set('x-render-time', `${ms}ms`);
  return response;
});
  • context is like Astro in a page: request, url, cookies, locals, redirect(), params, clientAddress.
  • next() runs the rest of the chain (more middleware, then the page) and resolves to a Response.
  • Return that response (possibly modified), or return your own and skip the page entirely.

Middleware runs for every request to server-rendered routes. For prerendered pages it runs once at build time with limited request data, so do not rely on headers or cookies there.

locals: passing data to pages

context.locals is an object that lives for one request. Middleware writes to it; pages, endpoints and server islands read it:

TypeScript
export const onRequest = defineMiddleware(async (context, next) => {
  const token = context.cookies.get('session')?.value;
  context.locals.user = token ? await findUserBySession(token) : null;
  return next();
});
ASTRO
---
const { user } = Astro.locals;
---
{user ? <p>Hi {user.name}</p> : <a href="/login">Log in</a>}

Type it in src/env.d.ts:

TypeScript
declare namespace App {
  interface Locals {
    user: { id: string; name: string } | null;
  }
}

Protecting routes

TypeScript
const protectedPrefixes = ['/dashboard', '/account', '/api/private'];

export const onRequest = defineMiddleware(async (context, next) => {
  const { pathname } = context.url;
  const token = context.cookies.get('session')?.value;
  context.locals.user = token ? await findUserBySession(token) : null;

  const needsLogin = protectedPrefixes.some((p) => pathname.startsWith(p));
  if (needsLogin && !context.locals.user) {
    return context.redirect(`/login?next=${encodeURIComponent(pathname)}`);
  }
  return next();
});

For API paths, return new Response(null, { status: 401 }) instead of a redirect.

Middleware is a convenience layer, not your only defence. Check authorisation again where the data is read or changed (in the endpoint or action), so a missed path pattern cannot leak data.

Chaining with sequence

Split concerns into small functions and run them in order:

TypeScript
import { sequence } from 'astro:middleware';

const logging = defineMiddleware(async (ctx, next) => {
  console.log(ctx.request.method, ctx.url.pathname);
  return next();
});

const auth = defineMiddleware(async (ctx, next) => { /* ... */ return next(); });

const headers = defineMiddleware(async (_ctx, next) => {
  const res = await next();
  res.headers.set('x-content-type-options', 'nosniff');
  res.headers.set('referrer-policy', 'strict-origin-when-cross-origin');
  return res;
});

export const onRequest = sequence(logging, auth, headers);

Order matters: code before next() runs first-to-last, code after it runs last-to-first (like layers of an onion).

Cookies

Astro.cookies (and context.cookies) is available on server-rendered pages, endpoints and middleware:

TypeScript
cookies.get('theme')?.value;         // read
cookies.has('session');              // check
cookies.set('theme', 'dark', {       // write
  path: '/',
  maxAge: 60 * 60 * 24 * 365,
  sameSite: 'lax',
  secure: true,
});
cookies.delete('session', { path: '/' });
cookies.get('prefs')?.json();        // helpers: .json(), .number(), .boolean()

Cookie attributes that matter for sessions:

  • httpOnly: true: JavaScript cannot read it, so XSS cannot steal it.
  • secure: true: sent over HTTPS only.
  • sameSite: 'lax' (or 'strict'): blocks most cross-site sending (CSRF defence).
  • path: '/' and a sensible maxAge.
  • Delete with the same path you used to set.

A tiny session flow

  1. A login endpoint verifies the password (hash comparison, never plain text) and creates a random session ID stored server-side (database, KV store).
  2. It sets session=<random id> as an httpOnly, secure cookie.
  3. Middleware looks the ID up on each request and fills locals.user.
  4. Logout deletes the stored session and the cookie.
TypeScript
// src/pages/api/login.ts
export const prerender = false;

export const POST: APIRoute = async ({ request, cookies, redirect }) => {
  const form = await request.formData();
  const user = await verifyCredentials(String(form.get('email')), String(form.get('password')));
  if (!user) return redirect('/login?error=1');

  const id = crypto.randomUUID();
  await saveSession(id, user.id);
  cookies.set('session', id, { httpOnly: true, secure: true, sameSite: 'lax', path: '/', maxAge: 60 * 60 * 24 * 7 });
  return redirect('/dashboard');
};

Astro also has a sessions feature, and libraries such as Lucia-style helpers or Auth.js wrappers exist. Check the current docs for their status; the manual flow above is how all of them work underneath. Never store the user object or secrets directly in a cookie unless it is signed and encrypted.

Try it: middleware chain

An onion model stand-in with sequence, next() and early return.

JS sequence and next

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A stand-in that builds Set-Cookie headers, with defaults that protect sessions.

JS Build Set-Cookie headers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does await next() return inside middleware?

    next() runs the remaining chain and resolves to a Response, which you can change or return.
  2. 2. How does a page read the user found by middleware?

    context.locals lives for one request and is exposed as Astro.locals in pages, endpoints and actions.
  3. 3. Which cookie flag prevents JavaScript from reading a session cookie?

    HttpOnly hides the cookie from document.cookie, reducing the damage of cross-site scripting.
  4. 4. In sequence(a, b, c), in what order does code AFTER await next() run?

    Handlers nest like an onion. After next() returns, control unwinds from the innermost handler outward.

Summary

  • src/middleware.ts exports onRequest; call next() to continue, or return your own response.
  • Put per-request data in locals; type it in env.d.ts.
  • sequence() chains small middleware; order matters.
  • Use httpOnly, secure, sameSite cookies; store session data server-side.
  • Authorise again where data is accessed; middleware alone is not enough.

Next: Astro Actions and Forms