Back to all posts

Type Safe process.env

Published 📅: ....
Last modified 📝: ....

Share this post on BlueskySee discussion on Bluesky


I've found myself copy and pasting the same TypeScript snippet to add type-safety for process.env.<X> references in my various projects. I figured I should just write a brief blog post to help myself with this in the future.

Use this snippet to override process.env types:

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      // Replace `KEY` with your env variables!
      KEY: string;
    }
  }
}

export {};

Recipe:

  • Create a types.d.ts file at the root of the project
  • Insert the above snippet
    • Make sure to replace KEY with your env variables!
  • Add ./types.d.ts to the includes array in tsconfig.json


Tags:

Loading...