Astro locals are a per-request object for passing data between middleware and the code that renders the response. You set a property on context.locals in src/middleware.ts, and every page, layout, component, endpoint and action handling that same request can read it as Astro.locals or context.locals. The object starts empty for each request, so nothing leaks between visitors.
This guide covers how Astro.locals works, how to type it, what belongs in it, and the two errors you hit when you use it wrong. Examples use Astro 7.
Key Takeaways
localsis created fresh for every request and is shared by middleware, pages, components, endpoints and actions.- Set values on it (
context.locals.user = ...); never replace the whole object, or Astro throwsLocalsReassigned.- Type it once by extending the global
App.Localsinterface insrc/env.d.ts.- On prerendered pages, middleware runs at build time, so locals holds build-time values only.
- Use locals for per-request data. Use cookies or sessions for data that must survive between requests.
What Astro.locals is
Every request that reaches Astro gets a context object: the URL, the Request, cookies, params, and a plain object called locals. Middleware receives that context first. Whatever it writes to context.locals is visible to everything that runs afterwards for the same request.
The names differ by where you are:
| Where | How you read it |
|---|---|
Middleware (src/middleware.ts) |
context.locals |
.astro pages, layouts and components |
Astro.locals |
API endpoints (src/pages/api/*.ts) |
context.locals |
Actions (src/actions/index.ts) |
context.locals in the handler’s second argument |
| Server islands | Astro.locals (the island is its own request, so middleware runs again) |
It is the same object in all of those places. Components nested five levels deep read the same Astro.locals as the page, which makes it the standard way to avoid passing a user prop through every layer.
Set locals in middleware
Middleware is where locals are usually filled. The Astro middleware guide covers the full API, and the official locals reference lists every place it is exposed; here is the minimal pattern:
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (context, next) => {
context.locals.requestId = crypto.randomUUID();
context.locals.startedAt = Date.now();
const sessionToken = context.cookies.get('session')?.value;
context.locals.user = sessionToken ? await getUserFromToken(sessionToken) : null;
return next();
});
async function getUserFromToken(token: string) {
// look the token up in your database or auth provider
return { id: '42', name: 'Ada', role: 'admin' as const };
}
Then read the values anywhere in the request:
---
// src/pages/account.astro
export const prerender = false;
const { user } = Astro.locals;
if (!user) {
return Astro.redirect('/login/');
}
---
<h1>Welcome back, {user.name}</h1>
Because the page returns early when user is missing, no protected markup is rendered for anonymous visitors.
Type locals with App. Locals
Without types, Astro.locals.user is an error in TypeScript. Astro declares an empty global interface, App.Locals, for you to extend. Put the declaration in src/env.d.ts (create it if your project doesn’t have one; the folder structure docs show where it sits):
// src/env.d.ts
interface User {
id: string;
name: string;
role: 'admin' | 'member';
}
declare namespace App {
interface Locals {
requestId: string;
startedAt: number;
user: User | null;
}
}
Now context.locals.user in middleware and Astro.locals.user in components are both typed, and autocomplete works in every file. If you set a property that isn’t declared, TypeScript flags it, which keeps the shape of locals documented in one place. The TypeScript props guide covers the rest of Astro’s typing helpers.
Read locals in endpoints and actions
API endpoints receive the same context object as middleware:
// src/pages/api/me.ts
import type { APIRoute } from 'astro';
export const prerender = false;
export const GET: APIRoute = ({ locals }) => {
if (!locals.user) {
return new Response('Unauthorized', { status: 401 });
}
return Response.json({ id: locals.user.id, name: locals.user.name });
};
Actions get it as the second argument of the handler:
// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';
export const server = {
renameProject: defineAction({
input: z.object({ id: z.string(), name: z.string().min(1) }),
handler: async (input, context) => {
if (context.locals.user?.role !== 'admin') {
throw new ActionError({ code: 'FORBIDDEN' });
}
// update the project here
return { ok: true };
},
}),
};
Middleware runs before actions, so the user check you wrote once applies to pages, endpoints and actions alike. The Astro Actions guide shows the client side of that call.
Chain several middleware functions
Bigger projects split middleware into small functions and run them in order with sequence(). Each one can read what the previous one set:
// src/middleware.ts
import { defineMiddleware, sequence } from 'astro:middleware';
const auth = defineMiddleware(async (context, next) => {
context.locals.user = null; // replace with your real lookup
return next();
});
const flags = defineMiddleware(async (context, next) => {
context.locals.betaUi = context.locals.user?.role === 'admin';
return next();
});
export const onRequest = sequence(auth, flags);
Order matters. flags depends on auth, so it has to come second.
The two locals errors
Astro protects the locals object so middleware further down the chain can rely on it. Two errors guard it, quoted here from Astro’s error reference.
LocalsReassigned: “locals must not be reassigned.” The message is “locals cannot be assigned directly.” It fires on code like this:
// src/middleware.ts (wrong)
context.locals = { user }; // throws LocalsReassigned
Set properties instead, or merge with Object.assign(context.locals, { user }). The LocalsReassigned fix has more cases, including integrations that trigger it.
LocalsNotAnObject: “Value assigned to locals is not accepted.” This one appears when something passes a number, string or other non-object as locals, for example a custom server calling Astro’s app handler. Astro’s hint: to remove information, use delete or set the property to undefined.
Locals on prerendered pages
Middleware runs for prerendered pages too, but it runs once at build time, not per visitor. Anything you put in locals during the build is baked into the HTML. That is useful for build-wide values such as a commit hash or a feature flag. It is wrong for per-user data: a static page can’t know who is visiting, and cookies aren’t available at build time.
If a page needs Astro.locals.user, render it on demand with export const prerender = false and an adapter. The Astro SSR guide explains when that trade-off is worth it, and the hybrid rendering tip shows how to mix static and on-demand routes in one project.
What to put in locals, and what not to
Good fits for locals:
- The current user or session record, looked up once per request
- A request ID for logging and tracing
- Feature flags or A/B variants resolved from a cookie
- A database or API client scoped to the request
- Timing data you log after
next()returns
Poor fits:
- Data that must survive to the next request. Locals disappears when the response is sent. Use cookies or Astro sessions.
- Secrets you don’t want rendered. Locals is server-only, but a component that prints
{Astro.locals.apiKey}will put it in the HTML. Keep secrets inastro:envserver variables. - Large caches shared across users. Use a module-level cache or your host’s cache instead.
Adapters can also add their own values. Hosts that expose platform features (bindings, geolocation, request metadata) sometimes do it through locals; check your adapter’s documentation for the exact property names, since they differ by platform.
If your site is mostly static content with no logged-in area, you may not need locals at all. Komal Nakrani Astro themes build to static HTML, which keeps hosting simple: middleware and locals only start to matter once you add a page that renders on demand.
FAQ
What is Astro.locals used for?
Astro.locals holds data for the current request, usually set by middleware. Common uses are the logged-in user, a request ID, feature flags and request-scoped clients. Pages, components, endpoints and actions all read the same object, so you avoid passing those values through props.
How do I add types to Astro.locals?
Extend the global App.Locals interface in src/env.d.ts with declare namespace App { interface Locals { ... } }. Every property you list becomes typed on both context.locals in middleware and Astro.locals in components.
Why do I get “locals must not be reassigned”?
Your code assigns a new object to locals (for example context.locals = { user }). Astro forbids that so other middleware keeps a stable object. Set individual properties, or use Object.assign(context.locals, { user }).
Does Astro.locals work on static pages?
Yes, but only with values available at build time, because middleware runs once during the build for prerendered pages. Per-visitor data such as the current user needs an on-demand route with export const prerender = false and an adapter.
What is the difference between Astro.locals and sessions?
Locals lives for one request and is gone when the response is sent. Sessions store data on the server between requests, keyed by a cookie. A common pattern is to read the session in middleware and put the result on locals for the rest of the request.