Problem statement

Environment variables are critical for configuring Node.js apps—think API keys, ports, or database URLs. But manually validating them is error-prone and tedious. What if you could define a schema, enforce types, and catch issues early? That’s where env-valid comes in—a lightweight, TypeScript-friendly validator I built to make this process painless.

Setup

Prerequisites: Node.js installed, basic project setup.
Installation:
bash

npm install env-valid

Basic Project:
Create a new folder, run npm init -y, and add a .env file (optional, since env-valid works with process.env directly).

Example .env:

PORT=3000
API_KEY=secret123
DEBUG=true

Note: "You don’t need dotenv—env-valid reads process.env by default, but it pairs well with it if you prefer."

Basic Example:

const { createEnvValidator } = require('env-valid');

const env = createEnvValidator({
  PORT: { type: 'number', default: 3000 },
  API_KEY: { type: 'string', required: true }
});

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send(`API Key: ${env.API_KEY}`);
});

app.listen(env.PORT, () => {
  console.log(`Server running on port ${env.PORT}`);
});

Advanced Usage:

const env = createEnvValidator({
  DEBUG: { type: 'boolean', default: false },
  HOSTS: { type: 'array' } // e.g., "a,b,c" or '["a", "b", "c"]'
});
console.log(env.DEBUG); // true/false based on "true", "yes", "1", etc.
console.log(env.HOSTS); // ["a", "b", "c"]

Custom Validation

const env = createEnvValidator({
  DB_URL: {
    type: 'string',
    validate: (val) => val.startsWith('mongodb://') || 'Must be a MongoDB URL'
  }
});

TypeScript Support

import { createEnvValidator } from 'env-valid';

const env = createEnvValidator({
  PORT: { type: 'number' as const, default: 3000 },
  API_KEY: { type: 'string' as const, required: true }
});

// Type-safe: env.PORT is number, env.API_KEY is string

"Full TypeScript support with autocompletion and type checking."

Why Use env-valid?

  • "Unlike dotenv, it validates types and schemas. Compared to envalid, it’s lighter and TypeScript-first. It’s flexible—use it standalone or with existing setups."
  • "Features like custom transforms, min/max constraints, and nested object validation make it versatile."

Conclusion and call to action

  • "With env-valid, you can stop worrying about invalid or missing env vars and focus on building your app. It’s open-source, so check it out on npm or GitHub!"
  • Links:

Npm: https://www.npmjs.com/package/env-valid

GitHub: https://github.com/yuvrajraghuvanshi/env-valid

What do you think? Try it in your next project and let me know your feedback—issues and PRs welcome!