dotenv-gad is an environment variable validation tool that brings type safety and schema validation to your Node.js and JavaScript applications. It extends dotenv
with features like:
- Type-safe environment variables
- Schema validation
- Schema composition
- Automatic documentation generation
- TypeScript support
- CLI tooling
- Secret management
npm install dotenv-gad
# or
yarn add dotenv-gad
# or
pnpm add dotenv-gad
- Create a schema file (
env.schema.ts
):
import { defineSchema } from "dotenv-gad";
export default defineSchema({
PORT: {
type: "number",
default: 3000,
docs: "Port to run the server on",
},
DATABASE_URL: {
type: "string",
required: true,
sensitive: true,
},
});
- Validate your environment:
import { loadEnv } from "dotenv-gad";
import schema from "./env.schema";
const env = loadEnv(schema);
console.log(`Server running on port ${env.PORT}`);
Command | Description |
---|---|
check |
Validate .env against schema |
sync |
Generate/update .env.example |
types |
Generate env.d.ts TypeScript types |
init |
Create starter schema |
fix |
Fixes environment issues |
docs |
Generates .env documentation |
npx dotenv-gad check
npx dotenv-gad types
- Type checking (string, number, boolean, array, object)
- Required/optional fields
- Default values
- Custom validation functions
- Environment-specific rules
{
API_URL: { type: 'url' },
EMAIL: { type: 'email' },
CONFIG: { type: 'json' },
TAGS: {
type: 'array',
items: { type: 'string' }
}
}
- Color-coded output
- Interactive fixes
- Strict mode
- Custom schema paths
- CI/CD friendly (comming soon!)
{
API_KEY: {
type: 'string',
sensitive: true, // Excluded from .env.example
validate: (val) => val.startsWith('sk_')
}
}
import express from "express";
import { loadEnv } from "dotenv-gad";
import schema from "./env.schema";
const env = loadEnv(schema);
const app = express();
app.listen(env.PORT, () => {
console.log(`Server running on port ${env.PORT}`);
});
Create next.config.js
:
const { loadEnv } = require("dotenv-gad");
const schema = require("./env.schema");
const env = loadEnv(schema);
module.exports = {
env: {
API_URL: env.API_URL,
},
};
Example error output:
Environment validation failed:
- DATABASE_URL: Missing required environment variable
- PORT: Must be a number (received: "abc")
- API_KEY: Must start with 'sk_' (received: "invalid")
{
DEBUG: {
type: 'boolean',
env: {
development: { default: true },
production: { default: false }
}
}
}
{
PASSWORD: {
type: 'string',
validate: (val) => val.length >= 8,
error: 'Password must be at least 8 characters'
}
}
{
FEATURES: {
type: 'array',
transform: (val) => val.split(',')
}
}
MIT © [Kasim Lyee]