DEV Community

Deepak Sharma
Deepak Sharma

Posted on

5

"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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay