0Pricing
TypeScript Academy · Lesson

Environment Variables and Config Typing

Type process.env with a validated config module.

Environment Variables and Config Typing is a free TypeScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

Typing process.env prevents runtime errors from missing or mistyped environment variables.

The Problem

process.env values are always string | undefined. Accessing them without checking causes bugs.
const port = process.env.PORT; // string | undefined
// server.listen(port); // could be undefined!

Module Augmentation for process.env

Extend ProcessEnv in a global declaration file to type known env vars.
declare global {
  namespace NodeJS {
    interface ProcessEnv {
      PORT: string;
      DATABASE_URL: string;
      NODE_ENV: 'development' | 'staging' | 'production';
    }
  }
}

Config Module Pattern

Create a typed config module that validates and exports env vars.
function requireEnv(key: string): string {
  const val = process.env[key];
  if (!val) throw new Error(`Missing env var: ${key}`);
  return val;
}
export const config = {
  port: parseInt(requireEnv('PORT')),
  dbUrl: requireEnv('DATABASE_URL'),
};

Zod for Env Validation

Validate env vars at startup with Zod for comprehensive runtime checking.
import { z } from 'zod';
const envSchema = z.object({
  PORT: z.string().transform(Number),
  DATABASE_URL: z.string().url(),
  NODE_ENV: z.enum(['development', 'production']),
});
export const env = envSchema.parse(process.env);

dotenv with TypeScript

Load .env files with dotenv before accessing process.env.
import 'dotenv/config';
// Or:
import dotenv from 'dotenv';
dotenv.config();

Strict env Access

Always access env through the config module, never directly via process.env in application code.

Config for Different Environments

Use NODE_ENV to load environment-specific configuration files.
const envFile = `.env.${process.env.NODE_ENV ?? 'development'}`;
dotenv.config({ path: envFile });

Secret Masking in Logs

Never log config objects that contain secrets. Mask sensitive fields.
console.log({ ...config, dbPassword: '***', apiKey: '***' });

Type-Safe Feature Flags

Type feature flag environment variables.
const flags = {
  enableBeta: process.env.ENABLE_BETA === 'true',
  logLevel: (process.env.LOG_LEVEL ?? 'info') as 'debug' | 'info' | 'warn',
};

Testing with Env Variables

Use a .env.test file and load it in test setup.
// tests/setup.ts
process.env.DATABASE_URL = 'sqlite:///:memory:';
process.env.NODE_ENV = 'test';

Quick Check

What is the TypeScript type of `process.env.PORT` without any augmentation?

Recap

Extend ProcessEnv via module augmentation or use a Zod config module to type and validate environment variables at startup. Always access env through a config module, never directly.

Frequently asked questions

Is the “Environment Variables and Config Typing” lesson free?

Yes — the full text of “Environment Variables and Config Typing” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Environment Variables and Config Typing”?

Type process.env with a validated config module. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Environment Variables and Config Typing” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Setting Up TypeScript with Node.js
  2. Typing Express Request and Response
  3. Typed Middleware and Error Handlers
  4. Environment Variables and Config Typing
← Back to TypeScript Academy