How to type Astro middleware locals

This article was published on Jul 07, 2023, and takes less than a minute to read.

Today I learned how to add types for Astro.locals global variable.

If you're using Astro's middleware with TypeScript and mutating this object, you might end up having TS issues like:

Property 'X' does not exist on type 'Locals'.

So here's what you should do in this case.

Inside the src folder, add a .env.d.ts file.

Then, you'll add the following code:

src/env.d.ts
declare namespace App {
  interface Locals {
   // add props here
  }
}

To have a consistent type inference and run time, ensure that your middleware matches exactly the type you expect.

Check out the sandbox with a demo.