DEV Community

Deepak Sharma
Deepak Sharma

Posted on

"TypeScript and process.env: A Match Made in Node.js Heaven"

Introduction:

Elevate your Node.js configuration game in just two simple steps! In this guide, we'll walk you through the process of adding TypeScript types to process.env, ensuring type safety and minimizing runtime errors. Transform your environment variables into a robust and error-resistant asset for your Node.js applications.

Step:1

Create /types/env.d.ts in the root of your project.
and add your types in ProcessEnv interface as shown below.

/types/env.d.ts



export {};

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      SUPABASE_ANON_KEY: string;
      SUPABASE_PROJECT_URL: string;
      ENV: "test" | "dev" | "prod";
    }
  }
}


Enter fullscreen mode Exit fullscreen mode

Step:2

you have created types of your process.env but typescipt dont know where you defined it , so add your types to ts.config.json as shown below.

ts.config.json



{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./types"]
  }
}



Enter fullscreen mode Exit fullscreen mode

πŸŽ‰πŸŽ‰ you have added types to your process.env.
you can check it in your code editor by auto suggestions.
process.env of nodejs code

Top comments (0)