Type-safe environment variable configuration
Quick Answer
Centralise all `process.env` access into a single typed config object so missing or wrong-type variables are caught at startup, not deep in runtime code.
1interface Env {
2 NODE_ENV: 'development' | 'production' | 'test';
3 PORT: number;
4 DATABASE_URL: string;
5}
6
7function getEnv(): Env {
8 const env = process.env;
9
10 return {
11 NODE_ENV: (env.NODE_ENV as Env['NODE_ENV']) || 'development',
12 PORT: parseInt(env.PORT || '3000', 10),
13 DATABASE_URL: env.DATABASE_URL || ''
14 };
15}
16
17export const config = getEnv();Scattering process.env access throughout a codebase makes it hard to track which variables are required and what types they should be. This pattern centralises all environment variable reading into a single config object with type coercions, making missing variables obvious and providing a single source of truth for all configuration.
Yes — for production apps, a library like `zod` or `envalid` gives you schema-level validation with clear error messages and supports `.env` file loading. This snippet is a lightweight alternative for simple projects.
This free typescript code snippet for environment config is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement environment config quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.