Skip to content

Using Astro locals

New Course Coming Soon:

Get Really Good at Git

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()
})
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my Astro Tutorial on The Valley of Code

Here is how can I help you: