Back to KB
Difficulty
Intermediate
Read Time
5 min

How to Validate Environment Variables in TypeScript (and Why You Should)

By Codcompass TeamΒ·Β·5 min read

Every developer has a story about a .env file causing a production outage. Maybe it was a missing DATABASE_URL that silently defaulted to undefined. Maybe NODE_ENV was set to staging instead of production, and staging API keys leaked into production traffic. Or perhaps a port number was accidentally typed as a string, and the server crashed with a cryptic type error.

Environment variables are the most common way to configure applications, but they have no built-in safety net. A typo, a missing value, or a misconfigured variable can reach production without a single warning β€” until your monitoring dashboard turns red.

In this tutorial, you'll learn how to define a schema for your environment variables, validate them automatically, generate TypeScript types from your schema, and catch configuration errors before they reach production.

The Problem: .env Files Have No Guardrails

Consider a typical .env file:

PORT=3000
DATABASE_URL=postgresql://localhost:5432/myapp
NODE_ENV=development
API_KEY=

Enter fullscreen mode Exit fullscreen mode

Now consider what happens when:

  • PORT accidentally gets set to "abc" β€” your server fails to bind
  • NODE_ENV is set to "staging" β€” your production environment uses staging credentials
  • API_KEY is blank β€” third-party API calls fail with 401s
  • DATABASE_URL uses http:// instead of postgresql:// β€” the connection pool silently fails

Without validation, each of these scenarios causes a runtime failure. With validation, they're caught in CI before deployment.

Introducing Schema-Based Validation

The fix is simple: define what each variable should look like, then check your .env file against that schema before anything runs.

A schema for the variables above might look like:

{
  "vars": {
    "PORT": {
      "type": "number",
      "required": true,
      "format": "port",
      "default": 3000
    },
    "DATABASE_URL": {
      "type": "string",
      "required": true,
      "format": "url"
    },
    "NODE_ENV": {
      "type": "string",

πŸŽ‰ Mid-Year Sale β€” Unlock Full Article

Base plan from just $4.99/mo or $49/yr

Sign in to read the full article and unlock all 635+ tutorials.

Sign In / Register β€” Start Free Trial

7-day free trial Β· Cancel anytime Β· 30-day money-back