Skip to main content
AllDevToolsHub
Back to all patterns

Generic API Key Format Validation

Security

Validates generic API keys: 20-64 alphanumeric characters with underscores and hyphens.

/^[A-Za-z0-9_\-]{20,64}$/

How it works

Many API keys follow a pattern of 20-64 URL-safe characters. This pattern validates the most common format. Specific APIs (Stripe, GitHub, etc.) have their own prefix conventions and exact lengths.

Test Cases

Should Match

  • sk_live_abcdefghijklmnopqrst
  • ghp_1234567890abcdefghijklmnopqrstu

Should NOT Match

  • short
  • has spaces in it
  • has@special!chars

Quick Summary

Validates generic API key format: 20-64 URL-safe characters (letters, digits, underscores, hyphens). Adjust the length range for specific APIs. Never log or expose API keys in client-side code.

Key Takeaways

Key Takeaways

  • 20-64 characters, adjust for your specific API key format
  • URL-safe characters only: letters, digits, underscores, hyphens
  • Many APIs use prefixes (sk_, pk_, ghp_), add prefix validation if needed
  • Never log, commit, or expose API keys, use environment variables
Use Cases

When to use it

  • Validating API key inputs in developer portal forms
  • Quick format check before making an API call
  • Detecting API key patterns in code for secret scanning
Watch out

Common Mistakes

  • Hardcoding API keys in source code, use environment variables or a secrets manager
  • Logging API keys in error messages or request logs
FAQ

Generic API Key Format Validation, Frequently Asked

How should I store API keys securely?

Use environment variables (.env files, not committed to git), a secrets manager (AWS Secrets Manager, HashiCorp Vault), or a key management service.

How do I detect leaked API keys in my codebase?

Use tools like git-secrets, truffleHog, or GitHub's secret scanning to detect committed secrets.