How to type Astro middleware locals

Publicado em 07 de jul. de 2023, e leva menos de 1 minuto para ler.

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.