REGEXVAULTv2.0
Security/Secrets & Config
Verified Safe

Environment Variable Secret Pattern (.env file) Regex for JavaScript

/^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\r\n#]{8,})$/m

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching environment variable secret pattern (.env file), ported and verified for JavaScript. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your JavaScript project — whether you're validating in an Express middleware, a Next.js API route, or a client-side form.

Javascript Implementation

Javascript
// Environment Variable Secret Pattern (.env file)
// ReDoS-safe | RegexVault — Security > Secrets & Config

const environmentVariableSecretPatternEnvFileRegex = /^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\r\n#]{8,})$/m;

function validateEnvironmentVariableSecretPatternEnvFile(input: string): boolean {
  return environmentVariableSecretPatternEnvFileRegex.test(input);
}

// Example
console.log(validateEnvironmentVariableSecretPatternEnvFile("DATABASE_PASSWORD=mySecretPassword123")); // true

Test Cases

Matches (Valid)
Rejects (Invalid)
DATABASE_PASSWORD=mySecretPassword123PORT=3000
STRIPE_SECRET_KEY=sk_live_4eC39HqLyjWDNODE_ENV=production
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG# PASSWORD_COMMENT=ignored
SHORT=ab

When to use this pattern

This pattern is drawn from the Security > Secrets & Config category and carries a ReDoS-safe certification. That matters for JavaScript developers because especially critical in long-running Node.js event loops where a ReDoS vulnerability can block the entire process. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

Even if .env is in .gitignore, it may be committed before the .gitignore was added, or in a squashed commit. Use git log -- .env to check history. Consider pre-commit hooks that refuse to commit .env files.

Technical Notes

.env files should never be committed to version control. Use .gitignore to exclude .env files. The pattern uses multiline mode to match line-by-line. Capture group 1=key name, group 2=value. Value must be at least 8 chars to reduce false positives.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern