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=
Now consider what happens when:
PORTaccidentally gets set to"abc"— your server fails to bind
NODE_ENVis set to"staging"— your production environment uses staging credentials
API_KEYis blank — third-party API calls fail with 401s
DATABASE_URLuseshttp://instead ofpostgresql://— 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",
"enum": ["development", "production", "test"],
"default": "development"
},
"API_KEY": {
"type": "string",
"required": true
}
}
}
This schema declares:
PORT must be a number, must be a valid port (1–65535), and defaults to 3000
DATABASE_URL must be a string, must be a valid URL, and is required
NODE_ENV can only be one of three values and defaults todevelopment
API_KEY must be a string and is required
Validating Your .env File
The tool we'll use is , is open source (MIT), has zero dependencies, and runs in under 100ms. Try it on your next project:
npx env-haven
Your future self — and your on-call rotation — will thank you.
SOCIAL SHARE CARD GENERATOR