no-hardcoded-credentials
Detects hardcoded passwords, API keys, tokens, and other sensitive credentials in source code. This rule is part of [`eslint-plugin-secure-coding`](https://www.
Keywords: hardcoded credentials, CWE-798, security, ESLint rule, API keys, passwords, tokens, secrets, environment variables, secret management, OWASP, credential security, auto-fix, LLM-optimized, code security
Detects hardcoded passwords, API keys, tokens, and other sensitive credentials in source code. This rule is part of eslint-plugin-secure-coding and provides LLM-optimized error messages that AI assistants can automatically fix.
⚠️ This rule warns by default in the recommended config.
Quick Summary
| Aspect | Details |
|---|---|
| CWE Reference | CWE-798 (Use of Hard-coded Credentials) |
| Severity | Critical (security vulnerability) |
| Auto-Fix | ✅ Yes (suggests environment variables or secret managers) |
| Category | Security |
| ESLint MCP | ✅ Optimized for ESLint MCP integration |
| Best For | All applications handling sensitive data, API integrations, database connections |
Vulnerability and Risk
Vulnerability: Embedding sensitive credentials (like passwords, API keys, or database connection strings) directly in the source code.
Risk: This leads to credential exposure in version control systems, making them accessible to any developer with repository access or attackers if the code is leaked. It also makes credential rotation difficult and error-prone.
Error Message Format
The rule provides LLM-optimized error messages (Compact 2-line format) with actionable security guidance:
🔒 CWE-798 OWASP:A04 CVSS:9.8 | Hardcoded Credentials detected | CRITICAL [SOC2,PCI-DSS,HIPAA,GDPR,ISO27001,NIST-CSF]
Fix: Review and apply the recommended fix | https://owasp.org/Top10/A04_2021/Message Components
| Component | Purpose | Example |
|---|---|---|
| Risk Standards | Security benchmarks | CWE-798 OWASP:A04 CVSS:9.8 |
| Issue Description | Specific vulnerability | Hardcoded Credentials detected |
| Severity & Compliance | Impact assessment | CRITICAL [SOC2,PCI-DSS,HIPAA,GDPR,ISO27001,NIST-CSF] |
| Fix Instruction | Actionable remediation | Follow the remediation steps below |
| Technical Truth | Official reference | OWASP Top 10 |
Rule Details
Hardcoded credentials are one of the most common security vulnerabilities. This rule detects passwords, API keys, tokens, and other sensitive values that are directly embedded in source code, which can be exposed in version control systems.
Why This Matters
| Issue | Impact | Solution |
|---|---|---|
| 🔒 Security | Credentials exposed in git history | Use environment variables |
| 🐛 Data Breach | API keys can be stolen from code | Secret management services |
| 🔐 Access Control | Passwords visible to all developers | AWS Secrets Manager, Vault |
| 📊 Compliance | Violates security best practices | CI/CD secret injection |
Detection Patterns
The rule detects:
- API Keys: Stripe keys (
sk_live_FAKE_KEY_FOR_TESTING), GitHub tokens (ghp_...), AWS keys (AKIA...) - JWT Tokens: Base64-encoded tokens with three parts
- OAuth Tokens: GitHub, GitLab, and similar OAuth tokens
- Passwords: Common weak passwords (
password,admin,123456) - Database Strings: Connection strings with embedded credentials
- Secret Keys: Long base64 or hex strings (32+ characters)
Examples
❌ Incorrect
// Hardcoded API key
const apiKey = 'sk_live_FAKE_LIVE_KEY_FOR_TESTING_PURPOSES_ONLY_1234567890';
// Hardcoded password
const password = 'admin123';
// Hardcoded JWT token
const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
// Database connection string with credentials
const dbUrl = 'mysql://user:password@localhost:3306/dbname';
// AWS access key
const awsKey = 'AKIAIOSFODNN7EXAMPLE';✅ Correct
// Environment variable
const apiKey = process.env.API_KEY;
// Secret manager
const password = await getSecret('database-password');
// Configuration service
const token = configService.get('JWT_TOKEN');
// Environment variable for database
const dbUrl = process.env.DATABASE_URL;
// AWS SDK with IAM roles (no keys needed)
const s3 = new AWS.S3(); // Uses IAM roleConfiguration
{
rules: {
'secure-coding/no-hardcoded-credentials': ['error', {
ignorePatterns: ['^test-'], // Ignore test credentials
allowInTests: false, // Allow in test files
minLength: 8, // Minimum credential length
detectApiKeys: true, // Detect API keys
detectPasswords: true, // Detect passwords
detectTokens: true, // Detect tokens
detectDatabaseStrings: true // Detect database strings
}]
}
}Options
| Option | Type | Default | Description |
|---|---|---|---|
ignorePatterns | string[] | [] | Regex patterns to ignore (e.g., ['^test-'] for test keys) |
allowInTests | boolean | false | Allow credentials in test files (.test.ts, .spec.ts) |
minLength | number | 8 | Minimum length for credential detection (except common passwords) |
detectApiKeys | boolean | true | Detect API keys (Stripe, AWS, etc.) |
detectPasswords | boolean | true | Detect common weak passwords |
detectTokens | boolean | true | Detect JWT and OAuth tokens |
detectDatabaseStrings | boolean | true | Detect database connection strings with credentials |
Ignoring Test Credentials
{
rules: {
'secure-coding/no-hardcoded-credentials': ['error', {
ignorePatterns: ['^test-', '^mock-', '^fake-']
}]
}
}Allowing Credentials in Test Files
{
rules: {
'secure-coding/no-hardcoded-credentials': ['error', {
allowInTests: true // Allows credentials in .test.ts and .spec.ts files
}]
}
}Rule Logic Flow
Best Practices
1. Use Environment Variables
// ✅ Good
const apiKey = process.env.STRIPE_API_KEY;
if (!apiKey) {
throw new Error('STRIPE_API_KEY is required');
}2. Use Secret Management Services
// ✅ Good - AWS Secrets Manager
import { SecretsManager } from '@aws-sdk/client-secrets-manager';
const client = new SecretsManager({ region: 'us-east-1' });
const secret = await client.getSecretValue({ SecretId: 'api-keys' });
const apiKey = JSON.parse(secret.SecretString).stripeKey;3. Use Configuration Services
// ✅ Good - Config service
import { ConfigService } from '@nestjs/config';
@Injectable()
export class ApiService {
constructor(private config: ConfigService) {}
getApiKey() {
return this.config.get<string>('API_KEY');
}
}4. Never Commit Credentials
# ✅ Good - Use .env files (gitignored)
echo "API_KEY=sk_live_FAKE_KEY_FOR_TESTING" >> .env
echo ".env" >> .gitignoreKnown False Negatives
The following patterns are not detected due to static analysis limitations:
Credentials from Config
Why: Config values not traced.
// ❌ NOT DETECTED - From config
const password = config.dbPassword;Mitigation: Use proper secrets management.
Environment Variables
Why: Env var content not analyzed.
// ❌ NOT DETECTED - Env var
const secret = process.env.API_KEY;Mitigation: Never hardcode or expose secrets.
Dynamic Credential Access
Why: Dynamic property access not traced.
// ❌ NOT DETECTED - Dynamic
const cred = credentials[type];Mitigation: Audit all credential access patterns.
Related Rules
no-sql-injection- Detects SQL injection vulnerabilitiesdatabase-injection- Comprehensive database securitydetect-eval-with-expression- Code injection detection
Resources
- CWE-798: Use of Hard-coded Credentials
- OWASP: Hardcoded Credentials
- 12 Factor App: Config
- AWS Secrets Manager
- HashiCorp Vault
Version History
- 1.3.0 - Initial release with comprehensive credential detection patterns
no-graphql-injection
Detects GraphQL injection vulnerabilities and DoS attacks. This rule is part of [`eslint-plugin-secure-coding`](https://www.npmjs.com/package/eslint-plugin-secu
no-hardcoded-session-tokens
The rule provides **LLM-optimized error messages** (Compact 2-line format) with actionable security guidance: