Skip to content

How to Secure API Keys

Key idea:

API key leaks are the #1 breach cause in 2026. Core rules: 1) Never commit keys to Git (use .env + .gitignore), 2) Rotate regularly (quarterly + on incident), 3) Scoped keys — minimum necessary permissions, 4) Secrets manager for production (Vault, AWS SM, GCP SM). GitHub Push Protection automatically blocks pushes with detected secrets.

Below: step-by-step, working examples, common pitfalls, FAQ.

Step-by-Step Setup

  1. NEVER hardcode in source code
  2. Use .env file + add to .gitignore
  3. Template: .env.example in git without actual values
  4. Production: environment variables or secrets manager
  5. Pre-commit hook: detect-secrets, git-secrets (AWS), trufflehog
  6. Git history scan: if accidentally committed — git filter-branch or BFG Repo-Cleaner
  7. Scoped keys: AWS IAM policies restrict actions/resources
  8. Rotate quarterly + log all usage (detect leaks early)

Working Examples

ScenarioConfig
.env file# .env (in .gitignore) STRIPE_API_KEY=sk_live_abc123 AWS_ACCESS_KEY_ID=AKIA... OPENAI_API_KEY=sk-proj-xxx # .env.example (in git) STRIPE_API_KEY=sk_live_xxx AWS_ACCESS_KEY_ID=xxx
Node.js reading .envrequire('dotenv').config(); const stripe = require('stripe')(process.env.STRIPE_API_KEY);
pre-commit hook (detect-secrets)pip install detect-secrets detect-secrets scan > .secrets.baseline # .pre-commit-config.yaml: repos: - repo: https://github.com/Yelp/detect-secrets rev: v1.4.0 hooks: [{id: detect-secrets}]
Emergency: remove key from git history# If key already in git — rotate IMMEDIATELY (key compromised) # Then clean history: git filter-branch --force --index-filter \ "git rm --cached --ignore-unmatch .env" \ --prune-empty --tag-name-filter cat -- --all git push --force origin main
AWS Secrets Managerimport boto3, json client = boto3.client('secretsmanager') secret = json.loads(client.get_secret_value(SecretId='prod/stripe')['SecretString']) api_key = secret['api_key']

Common Pitfalls

  • Committing .env — most common mistake. Always .gitignore first
  • Key in logs: console.log(req) dumps headers with Authorization. Mask secrets in logger
  • Frontend code exposes key: client-side JS — ALL visible. Use backend proxy
  • Rotation — skipped in hot codebases. Automate via scripts + alarms on expiring keys
  • Same key in dev + prod — leak one = leak all. Separate keys per env is mandatory
HeadersCSP, HSTS, X-Frame-Options, etc.
SSL/TLSEncryption and certificate
ConfigurationServer settings and leaks
Grade A-FOverall security score

Why teams trust us

OWASP
guidelines
15+
security headers
<2s
result
A–F
security grade

How it works

1

Enter site URL

2

Security headers analyzed

3

Get grade A–F

What Does the Security Analysis Check?

The tool checks HTTP security headers, SSL/TLS configuration, server info leaks, and protection against common attacks (XSS, clickjacking, MIME sniffing). A grade fromA to F shows overall security level.

Header Analysis

Checking Content-Security-Policy, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and more.

SSL Check

TLS version, certificate expiry, chain of trust, HSTS support.

Leak Detection

Finding exposed server versions, debug modes, open configs, and directories.

Report with Recommendations

Detailed report explaining each issue with specific steps to fix it.

Who uses this

Security teams

HTTP header audit

DevOps

config verification

Developers

CSP & HSTS setup

Auditors

compliance checks

Common Mistakes

Missing Content-Security-PolicyCSP is the primary XSS defense. Without it, script injection is much easier.
Missing HSTS headerWithout HSTS, HTTPS-to-HTTP downgrade attacks are possible. Enable Strict-Transport-Security.
Server header exposes versionServer: Apache/2.4.52 helps attackers find exploits. Hide the version.
X-Frame-Options not setSite can be embedded in iframe for clickjacking. Set DENY or SAMEORIGIN.
Missing X-Content-Type-OptionsWithout nosniff, browsers may misinterpret file types (MIME sniffing).

Best Practices

Start with basic headersMinimum: HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy. Takes 5 minutes.
Implement CSP graduallyStart with Content-Security-Policy-Report-Only, monitor violations, then enforce.
Hide server headersRemove Server, X-Powered-By, X-AspNet-Version from responses.
Configure Permissions-PolicyRestrict camera, microphone, geolocation access — only what is actually used.
Check after every deploySecurity headers can be overwritten during server configuration updates.

Get more with a free account

Security check history and HTTP security header monitoring.

Sign up free

Learn more

Frequently Asked Questions

GitHub Push Protection — what is it?

Bloom filter + regex detection on commits at push. Catches AWS, Stripe, Google, OpenAI keys and other common patterns. Enable in repo settings.

How to know a key leaked?

Scan history: trufflehog. Monitor provider alerts (AWS CloudTrail, Stripe webhook). Enable Secret Scanning in GitHub (free for public repos).

Vault, AWS SM, or .env?

.env for local dev + staging. Vault/SM for production — enable audit, rotation, fine-grained access. For early-stage — AWS SM cheap and safe.

Client-side keys (e.g. Google Maps)?

Restrict by referer/origin. Google Maps key bound to *.example.com — attacker domain useless. Not 100% protection but raises bar.