Tips: Using Astro locals

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Astro locals are a great way to share variables between middleware and page components (note: not layouts, as discussed in another post).

You can add a property in the src/middleware.ts file:

import type { MiddlewareHandler } from 'astro'

export const onRequest: MiddlewareHandler = async (context, next) => {
  context.locals.test = 'test'
  return await next()
}

and access it in the page component:

---
console.log(Astro.locals.test)
---

....

…this unlocks a few useful scenarios.

Mostly setting some property in a page, and using it in the middleware.

Note that if you add a property in the middleware you’ll see this TS issue:

To fix this problem, add to src/env.d.ts the type of the new property:

/// <reference types="astro/client" />

declare namespace App {
  interface Locals {
    test: string
  }
}

and define your middleware in this way:

import { defineMiddleware } from 'astro:middleware'

export const onRequest = defineMiddleware(async (context, next) => {
  context.locals.test = 'test'

  return await next()
})

UPDATE: somehow this didn’t work for me, I used this instead (src https://github.com/withastro/astro/issues/7394#issuecomment-2212516410):

/// <reference types="astro/client" />

declare global {
  namespace App {
    interface Locals extends Record<string, any> {
      test: string
    }
  }
}

Lessons in this unit:

0: Introduction
1: Fix .md in links
2: Moving a simple site to Astro
3: Astro, fix Form error “Content-Type was not one of…”
4: Astro page layout and middleware execution order
5: Astro, set caching headers
6: Astro, set response header
7: Deploying an Astro + PostgreSQL app on Railway
8: ▶︎ Using Astro locals
9: Using Cloudflare Turnstile on a Astro form
10: Using reCAPTCHA on a Astro form
11: Why not write logic in Astro layouts