secure-env-check
v1.0.0
Published
A production-ready environment variable validator that prevents common configuration mistakes, detects weak secrets, and guards against accidental .env commits.
Maintainers
Readme
🔒 secure-env-check
A zero-dependency, production-ready library that validates environment variables, detects weak secrets, and guards against accidental
.envcommits.
Why?
Developers often ship code with:
- ❌ Missing environment variables that crash at runtime
- ❌ Weak or guessable secrets (
password,123456,changeme) - ❌ Invalid configuration values (e.g.
NODE_ENV=stagin) - ❌
.envfiles accidentally committed to git
secure-env-check catches all of these before your app starts — with clear, coloured error messages and zero setup overhead.
Installation
npm install secure-env-checkQuick Start
import { validateEnv } from "secure-env-check";
validateEnv({
DB_URL: "required", // must be present and non-empty
JWT_SECRET: "strong", // must be present AND cryptographically strong
NODE_ENV: ["development", "production"], // must be one of these values
});That's it. If anything is wrong, you'll see:
🔒 secure-env-check — validation results
❌ DB_URL is missing
❌ JWT_SECRET is weak. Too short (3 chars). Use at least 12 characters
❌ NODE_ENV must be one of: development, production
⚠️ .env is tracked by git — this is a security risk! Add it to .gitignore immediately.Schema Rules
| Rule | Type | Description |
|------|------|-------------|
| "required" | string | Variable must be present and non-empty |
| "strong" | string | Variable must be a strong secret (≥12 chars, mixed character types, no common patterns) |
| ["a", "b"] | string[] | Variable must be one of the allowed values |
| { type: "regex", pattern: "..." } | object | Variable must match a regex pattern |
| { type: "oneOf", values: [...] } | object | Variable must be one of the values (advanced form) |
API Reference
validateEnv(schema, options?)
Validates process.env against the given schema.
Parameters:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| strict | boolean | false | Throw errors even in development mode |
| checkGit | boolean | true | Check if .env is tracked by git |
| envFile | string | ".env" | Which dotenv file to check for git tracking |
| env | object | process.env | The env object to validate (useful for testing) |
| silent | boolean | false | Suppress console output (still throws in strict/production) |
| rules | Function[] | [] | Custom validation rule functions |
Returns: { valid: boolean, errors: string[], warnings: string[] }
Behaviour:
- In production (
NODE_ENV=production): throws anErroron validation failure - In development: logs errors/warnings but does NOT throw (unless
strict: true)
checkSecretStrength(value)
Check whether a string is strong enough to be used as a secret.
import { checkSecretStrength } from "secure-env-check";
const { strong, reasons } = checkSecretStrength("my-jwt-secret");
// strong: false
// reasons: ["Contains a common / predictable pattern"]Strength rules:
- ≥ 12 characters
- Must NOT contain common patterns (
password,secret,123456, etc.) - Must contain at least 3 of: uppercase, lowercase, digit, symbol
checkEnvFileTracked(filename?)
Detect if a dotenv file is tracked by git.
import { checkEnvFileTracked } from "secure-env-check";
const { tracked, message } = checkEnvFileTracked(".env");
if (tracked) {
console.warn(message);
}Advanced Usage
Custom Rules
Add project-specific validation logic via the rules option:
validateEnv(
{ DB_URL: "required" },
{
rules: [
(env) => {
if (env.DB_URL && !env.DB_URL.startsWith("postgres://")) {
return { error: "DB_URL must be a PostgreSQL connection string" };
}
return null;
},
(env) => {
if (!env.LOG_LEVEL) {
return { warning: "LOG_LEVEL is not set — defaulting to 'info'" };
}
return null;
},
],
}
);Each rule function receives the env object and returns one of:
null— no issue{ error: "..." }— an error message{ warning: "..." }— a warning message
Regex Validation
validateEnv({
EMAIL: {
type: "regex",
pattern: "^.+@.+\\..+$",
message: "EMAIL must be a valid email address",
},
});Strict Mode
Force errors to throw even in development:
validateEnv(
{ API_KEY: "required" },
{ strict: true }
);
// Throws Error if API_KEY is missing, regardless of NODE_ENVCLI Usage
# Auto-detect common env vars
npx secure-env-check
# Use a JSON schema file
npx secure-env-check --schema ./env.schema.json
# Strict mode
npx secure-env-check --strict
# Custom .env file
npx secure-env-check --env-file .env.local
# Skip git check
npx secure-env-check --no-gitSchema File Format (env.schema.json)
{
"DATABASE_URL": "required",
"JWT_SECRET": "strong",
"NODE_ENV": ["development", "staging", "production"],
"REDIS_URL": "required"
}GitHub Actions Integration
Add to your CI pipeline to catch misconfigured environments early:
name: Env Check
on: [push, pull_request]
jobs:
validate-env:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npx secure-env-check --schema env.schema.json --strict
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
JWT_SECRET: ${{ secrets.JWT_SECRET }}
NODE_ENV: productionSecurity Philosophy
- Fail fast, fail loud. Misconfigured environments should never silently reach production.
- Secrets must be strong. Weak secrets are as bad as no secrets. We enforce length, diversity, and pattern blacklists.
.envmust never be in git. We proactively detect this and warn you.- Zero dependencies. Fewer dependencies = smaller attack surface. This library uses only Node.js built-ins.
- Developer-friendly. Clear, coloured messages tell you exactly what's wrong and how to fix it.
Production vs Development Behaviour
| | Development | Production |
|---|---|---|
| Missing/invalid vars | ⚠️ Logs errors to console | 💥 Throws Error (process crashes) |
| Weak secrets | ⚠️ Logs errors to console | 💥 Throws Error |
| .env tracked by git | ⚠️ Warning | ⚠️ Warning |
| strict: true | 💥 Throws Error | 💥 Throws Error |
Example Error Messages
❌ JWT_SECRET is weak. Too short (3 chars). Use at least 12 characters. Weak character diversity. Include uppercase, lowercase, digits, and symbols
❌ DB_URL is missing
❌ NODE_ENV must be one of: development, production
⚠️ .env is tracked by git — this is a security risk! Add it to .gitignore immediately.Project Structure
secure-env-check/
├── index.js # Core library (validateEnv, checkSecretStrength, checkEnvFileTracked)
├── cli.js # CLI entry point (npx secure-env-check)
├── package.json
├── README.md
├── LICENSE
├── .gitignore
└── test/
└── index.test.js # Comprehensive test suiteRequirements
- Node.js ≥ 16
- ESM (uses
import/export)
