@danielszlaski/envguard
v0.1.11
Published
EnvGuard - Keep your environment variables in sync with your codebase (Free version)
Maintainers
Readme
EnvGuard CLI
Static analysis for environment variables you can actually trust
EnvGuard helps you keep environment variables clean, documented, and consistent across your entire codebase.
No more guessing, broken deploys, or outdated .env.example files.
Why EnvGuard exists
Environment variables tend to rot over time. Teams move fast, infrastructure evolves, and configuration quietly drifts.
Common pain points:
.env.exampledoes not match real usage anymore- New developers waste time figuring out required variables
- Secrets accidentally leak into repositories
- Old variables linger forever with no owner
- CI fails late due to missing configuration
- Serverless configs and code fall out of sync
EnvGuard was built to eliminate this entire class of problems automatically.
What EnvGuard does for you
EnvGuard continuously validates how environment variables are defined, used, and documented.
- Scans your codebase for environment variable usage
- Compares usage with
.envand.env.example - Detects missing, unused, and hardcoded variables
- Understands fallback patterns and adjusts severity intelligently
- Keeps
.env.examplefiles accurate and up to date - Supports multiple
.envfiles in subdirectories (monorepo-friendly!) - Integrates cleanly into Git hooks and CI pipelines
Result: fewer runtime surprises, faster onboarding, and safer releases.
Need More Functionality? Consider EnvGuard Pro
If your team needs more than local/basic checks, EnvGuard Pro is the recommended option: https://envguard.pl
What stands out in Pro (from envguard.pl):
- SARIF output for GitHub Security (
--format sarif) for CI/compliance workflows - AWS validation (
--aws,--aws-deep) for SSM + Secrets checks with profile/region-aware context - Shell env file support (
envFiles/--env-files) to scanexportvariables from scripts likeset-env.sh - Deeper Serverless/AWS coverage across provider, function, and AWS resources sections, including nested secret lookups
If you are looking for broader infrastructure coverage and CI-ready reporting, go with Pro.
Installation
Option 1: Install globally
npm install -g @danielszlaski/envguardAfter installation, use the short command:
envguard scanOption 2: Use with npx (no installation needed)
npx @danielszlaski/envguard scanUsage
Note: The examples below use
envguard(short form), which works after installation. If using npx without installation, usenpx @danielszlaski/envguardinstead.
Git Hook Integration (Pre-commit/Pre-push)
Automatically run envguard before every commit or push to catch environment variable issues early:
# Install a pre-commit hook (runs before each commit)
envguard install-hook
# Or install a pre-push hook (runs before each push)
envguard install-hook --type pre-push
# Force overwrite existing hook
envguard install-hook --forceOnce installed, the hook will automatically run envguard scan --ci before each commit (or push). If issues are found, the commit/push will be blocked until you fix them.
Bypass the hook when needed:
git commit --no-verify
git push --no-verifyRemove the hook:
envguard uninstall-hook
# Or for pre-push hook
envguard uninstall-hook --type pre-pushHow it works:
- The hook creates a script in
.git/hooks/pre-commit(orpre-push) - Before each commit/push, it runs
envguard scan --ci - If issues are found, the operation is blocked
- Team members need to install the hook individually (it's not tracked in git)
Scan for issues
envguard scan
# Exclude specific file patterns from scanning
envguard scan --exclude "tests/**,scripts/**"
# Ignore specific variables (merged with config ignoreVars)
envguard scan --ignore-vars MY_VAR,ANOTHER_VARExample output:
Loaded config from ../.envguardrc.json
Scanning env sources:
• serverless.yml
Unused variables:
• NODE_ENV
• STAGE
• OKTA_DOMAIN
• OKTA_CLIENT_ID
Skipped known runtime/ignored variables (use --strict to show):
Custom (from config/CLI): LOCALHOST, STAGE
Serverless Framework: IS_OFFLINE, SLS_OFFLINE
CI/CD: CI
AWS Lambda: AWS_REGION
──────────────────────────────────────────────────
Info: 5
Run `envguard fix` to auto-generate .env.example filesAuto-generate .env.example
envguard fixThis will create/update .env.example files with:
- All environment variables used in your code
- Comments showing where each variable is used
- Format hints for common variable types (URLs, ports, etc.)
- Creates
.env.examplenext to each.envfile (great for monorepos!)
Example generated .env.example:
# Auto-generated by envguard
# Do not put actual secrets in this file - use .env instead
# Used in: src/db/connection.ts:12, src/models/user.ts:5
# Format: postgresql://user:pass@host:5432/db
DATABASE_URL=
# Used in: src/payment.js:23
# Format: sk_test_...
STRIPE_SECRET_KEY=
# Used in: src/server.ts:8
# Format: 3000
PORT=CI/CD Integration
Use the --ci flag in your CI pipeline to fail builds if environment variables are out of sync:
envguard scan --ciThis will exit with code 1 if issues are found.
GitHub Actions Setup
EnvGuard integrates seamlessly with GitHub Actions to validate your environment variables on every pull request or push.
Quick Setup (Recommended)
Create .github/workflows/envguard.yml in your repository:
name: Environment Variables Check
on:
pull_request:
branches: [main]
push:
branches: [main, develop]
jobs:
envguard:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: Run EnvGuard check
run: npx @danielszlaski/envguard scan --ciThat's it! No installation needed - npx downloads EnvGuard on demand.
Strict Mode in CI
Enable strict mode to catch all variables including runtime-provided ones:
- name: Run EnvGuard check (strict)
run: npx @danielszlaski/envguard scan --ci --strictWeekly Audit
Schedule weekly checks to catch configuration drift:
name: Weekly Environment Audit
on:
schedule:
- cron: '0 9 * * MON' # Every Monday at 9am UTC
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20.x'
- run: npx @danielszlaski/envguard scan --ci --strict
- name: Create issue if problems found
if: failure()
uses: actions/github-script@v7
with:
script: |
github.rest.issues.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: '⚠️ Environment Variables Out of Sync',
body: 'Weekly EnvGuard audit found issues. Run `npx @danielszlaski/envguard scan` locally for details.',
labels: ['env-config', 'maintenance']
})Caching for Faster Runs
Speed up CI runs by caching npx downloads:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
cache: 'npm' # Caches npx downloads
- name: Run EnvGuard
run: npx @danielszlaski/envguard scan --ciOther CI Platforms
GitLab CI (.gitlab-ci.yml):
envguard:
image: node:20
script:
- npx @danielszlaski/envguard scan --ci
only:
- merge_requestsCircleCI (.circleci/config.yml):
version: 2.1
jobs:
envguard:
docker:
- image: cimg/node:20.0
steps:
- checkout
- run: npx @danielszlaski/envguard scan --ciTravis CI (.travis.yml):
language: node_js
node_js:
- '20'
script:
- npx @danielszlaski/envguard scan --ciSupported Languages & Frameworks
JavaScript/TypeScript
- JavaScript (
.js,.mjs,.cjs) - TypeScript (
.ts,.tsx) - JSX (
.jsx)
Detects:
process.env.VAR_NAMEprocess.env['VAR_NAME']const { VAR_NAME } = process.env
Serverless Framework
- Automatically detects
serverless.ymlandserverless.yamlfiles - Scans
provider.environmentsection - Scans function-level
environmentsections - Detects references to external sources (SSM, Secrets Manager, etc.)
- Validates that all defined variables are used in code
- Reports variables used in code but not defined in serverless.yml
Configuration
EnvGuard works out of the box with sensible defaults. It automatically excludes:
node_modulesdistbuild.git
Custom Configuration
Create a configuration file in your project root. The following file names are recognised (in priority order): .envguardrc.json, .envguardrc, envguard.config.json, or a "envguard" key in package.json.
{
"ignoreVars": [
"MY_CUSTOM_VAR",
"ANOTHER_VAR",
"COMPANY_INTERNAL_VAR"
],
"strict": false,
"detectFallbacks": true,
"exclude": [
"**/build/**",
"**/tmp/**"
]
}Configuration options:
ignoreVars(string[]): Custom environment variables to ignore in non-strict mode. These will be treated like AWS_REGION and won't trigger warnings.strict(boolean): Enable strict mode by default (can be overridden with CLI flag)detectFallbacks(boolean): Detect fallback patterns in code and treat them as warnings instead of errors (default:true)exclude(string[]): Additional file patterns to exclude from scanning
Alternative: package.json
You can also add configuration to your package.json:
{
"envguard": {
"ignoreVars": ["MY_CUSTOM_VAR"],
"strict": false
}
}Use case for ignoreVars:
- Company-wide variables that are always available (injected by infrastructure)
- Framework-specific variables you don't need to track
- Variables provided by your deployment platform (Vercel, Netlify, etc.)
- Custom variables for GitHub Apps or CI/CD integrations
Priority: CLI flags > .envguardrc.json > package.json > defaults
GitHub Apps & CI/CD:
When using EnvGuard as a GitHub App or in CI/CD pipelines, commit your .envguardrc.json to the repository. This ensures consistent behavior across all environments and team members.
Fallback Detection (Smart Severity)
EnvGuard automatically detects common defensive patterns in your code and adjusts issue severity accordingly. When a variable is used with a fallback or default value, it's treated as a WARNING instead of an ERROR.
Detected patterns:
// Default values with || or ??
const port = process.env.PORT || 3000; // WARNING
const url = process.env.API_URL ?? 'localhost'; // WARNING
// Ternary operators
const env = process.env.NODE_ENV ? 'set' : 'dev'; // WARNING
// Conditional checks
if (process.env.FEATURE_FLAG) { } // WARNING
if (!process.env.DEBUG) { } // WARNING
// Destructuring with defaults
const { LOG_LEVEL = 'info' } = process.env; // WARNING
// Optional chaining
const value = process.env?.OPTIONAL_VAR; // WARNING
// No fallback - strict requirement
const apiKey = process.env.API_KEY; // ERRORSeverity levels:
- ERROR (✖): Variable used without any safety mechanism - likely to cause runtime errors
- WARNING (⚠): Variable used with fallback/default - code handles missing values
- INFO (ℹ): Unused variables or optional documentation issues
Disable fallback detection:
If you prefer all missing variables to be treated as errors regardless of fallbacks:
# CLI flag
envguard scan --no-detect-fallbacks
# Config file
{
"detectFallbacks": false
}Why this feature exists:
Not all missing environment variables are equal. Variables with defensive fallbacks are less critical than those that will cause undefined errors. This feature helps you prioritize what to fix first while still being aware of all env var usage.
Limitations:
Fallback detection uses regex patterns and catches common cases (~80% of real-world usage). Complex patterns like function calls with fallbacks or deeply nested conditionals may not be detected. For strict validation, use --no-detect-fallbacks or set detectFallbacks: false in your config.
Hardcoded Value Detection
EnvGuard detects environment variables that are assigned directly in code instead of being read from the environment. These are reported as warnings because the value exists at runtime, but the pattern itself is a code smell — it bypasses .env management entirely.
Detected patterns:
process.env.MY_VAR = 'some-value'; // WARNING — hardcoded assignment
process.env['API_KEY'] = 'sk_live_...'; // WARNING — hardcoded assignmentHardcoded assignments are reported in their own group in the scan output, separate from missing or unused variables.
Monorepo Support
EnvGuard automatically detects all .env files in your project, including subdirectories. When you run envguard fix, it creates a .env.example file next to each .env file it finds.
Example structure:
project/
├── .env → generates .env.example
├── src/
│ └── lambda1/
│ ├── .env → generates lambda1/.env.example
│ └── handler.js
└── services/
└── api/
├── .env → generates api/.env.example
└── server.jsEach .env.example only includes variables used in that directory and its subdirectories.
Serverless Framework Support
EnvGuard treats serverless.yml as a first-class source of environment variables, so Lambda-focused teams can keep configuration and code in sync without maintaining parallel .env files.
How EnvGuard parses serverless.yml
The built-in src/parser/serverlessParser.ts keeps things simple and predictable:
provider.environmententries are read exactly as you define them, whether the value is hardcoded or points to something like${ssm:/myapp/db-url}.- Each
functions.<name>.environmentblock is scanned independently, so function-specific overrides are preserved. - Every extracted variable is compared against actual usage in your code to highlight gaps.
Example snippet that EnvGuard understands:
provider:
environment:
DATABASE_URL: ${ssm:/myapp/db-url}
API_KEY: hardcoded-value
functions:
myFunction:
environment:
FUNCTION_VAR: some-valueScan output for serverless.yml
Checking src/lambda/serverless.yml
Found 3 variable(s) in serverless.yml
Found 2 variable(s) used in code
⚠ Unused variables in serverless.yml:
• DATABASE_URL
✖ Missing from serverless.yml:
• LOG_LEVEL
Used in: src/lambda/handler.jsCurrent parser limits
To keep the parser lightweight, a few parts of serverless.yml are intentionally ignored today:
resources.Resourcesblocks (such as ECS task definitions or standalone Lambdas)- Nested
${ssm:}path resolution inside custom objects ${secretsmanager:}references- Nested secret keys like
secrets.host
If you rely on those sections, you can still run EnvGuard—it will simply skip them while continuing to validate every provider.environment and function-level environment entry that it finds.
Why it matters
- No .env required –
serverless.ymlacts as the single source of truth - Function-level coverage – highlights mismatches between shared and per-function variables
- Smart filtering – known AWS/runtime variables stay out of your reports (use
--strictto include them) - CI/CD friendly –
envguard scan --cican block deployments when your configuration and code drift apart
Commands
envguard scan- Scan for issues and display reportenvguard scan --ci- Scan and exit with error code if issues foundenvguard scan --strict- Report all variables including known runtime variablesenvguard scan --no-detect-fallbacks- Treat all missing variables as errors (ignore fallback detection)envguard scan --exclude <patterns>- Comma-separated glob patterns to exclude (merged with configexclude)envguard scan --ignore-vars <vars>- Comma-separated variables to ignore (merged with configignoreVars)envguard fix- Auto-generate.env.exampleenvguard install-hook- Install a Git pre-commit hook to run checks automaticallyenvguard install-hook --type pre-push- Install a pre-push hook insteadenvguard install-hook --force- Overwrite existing hook if presentenvguard uninstall-hook- Remove the envguard Git hookenvguard uninstall-hook --type pre-push- Remove the pre-push hook
Strict Mode
By default, EnvGuard filters out well-known runtime variables that don't need to be explicitly defined:
AWS Lambda variables: AWS_REGION, AWS_LAMBDA_FUNCTION_NAME, etc.
Node.js runtime: NODE_ENV, PATH, etc.
CI/CD environments: CI, GITHUB_ACTIONS, etc.
Serverless Framework: IS_OFFLINE, SLS_OFFLINE, etc.
Use --strict mode to report ALL variables including these runtime-provided ones:
envguard scan --strictExample output (non-strict):
Skipped known runtime variables (use --strict to show):
Serverless Framework: IS_OFFLINE, SLS_OFFLINE
CI/CD: CI
AWS Lambda: AWS_REGIONDevelopment
# Install dependencies
npm install
# Build
npm run build
# Run locally
npm start scanLicense
MIT 2026 Daniel Szlaski
EnvGuard CLI
Supported platforms and frameworks
- Node.js JavaScript and TypeScript
- Serverless Framework projects
- Monorepos with nested services
- CI environments including GitHub Actions, GitLab CI, CircleCI, Travis
Installation
Global installation
npm install -g @danielszlaski/envguardThen run:
envguard scanNo installation using npx
npx @danielszlaski/envguard scanCore commands
Scan for issues
envguard scanFinds:
- Missing variables
- Unused variables
- Hardcoded assignments
- Drift between code and configuration
Auto generate .env.example
envguard fixAutomatically creates or updates .env.example files with:
- All variables actually used
- Usage locations in code
- Helpful format hints
- Zero real secrets
Each .env.example is generated next to its corresponding .env, making it ideal for monorepos.
Smart severity detection
EnvGuard understands intent.
process.env.API_KEY // ERROR
process.env.PORT || 3000 // WARNING
process.env.DEBUG && log() // WARNING- Errors indicate real runtime risk
- Warnings highlight defensive or optional usage
- Noise is reduced without hiding problems
Fallback detection can be disabled if strict enforcement is required.
Git hook integration
Catch configuration issues before they ever reach CI.
envguard install-hookOptions:
- Pre commit or pre push hooks
- Forced overwrite
- Easy removal
Hooks run envguard scan --ci automatically and block commits when issues are found.
CI and automation friendly
EnvGuard is designed for automation first.
envguard scan --ci- Exits with non zero code on errors
- Perfect for CI pipelines
- No interactive output
- Fast and deterministic
Works out of the box with GitHub Actions, GitLab CI, CircleCI, and more.
Serverless Framework support
EnvGuard treats serverless.yml as a first class configuration source.
It:
- Extracts provider and function level variables
- Validates that all variables are actually used
- Detects missing definitions referenced in code
- Understands SSM, Secrets Manager, and CloudFormation references
- Skips AWS runtime variables automatically unless strict mode is enabled
This prevents silent misconfiguration in Lambda based systems.
Configuration
EnvGuard works without configuration, but can be customized via:
.envguardrc.jsonenvguard.config.jsonpackage.json
Example:
{
"ignoreVars": ["COMPANY_INTERNAL_VAR"],
"strict": false,
"detectFallbacks": true,
"exclude": ["**/build/**"]
}Priority: CLI flags → config file → package.json → defaults
Who EnvGuard is for
EnvGuard is ideal for:
- Teams onboarding new developers
- Projects with growing configuration surface area
- Serverless and microservice architectures
- Repositories with strict CI requirements
- Anyone tired of debugging missing env vars at runtime
If environment variables ever broke your deploy, EnvGuard pays for itself immediately.
License
MIT © 2026 Daniel Szlaski
