SecretDrop
Back to Blog
Security API Keys Best Practices Developer Guide

API Key Management Best Practices

| Aleksandar Jovanovic
Server room with blue lighting representing API key infrastructure security

A 2023 GitGuardian report found over 10 million secrets exposed in public GitHub repositories — and API keys were the most common type. API key management best practices are not theoretical concerns reserved for enterprise security teams. They are daily operational requirements for any developer who authenticates against third-party services, deploys to cloud infrastructure, or collaborates across teams. Poor key hygiene leads to breaches, and breaches lead to very expensive conversations.

This guide covers the full lifecycle: generation, storage, rotation, sharing, and revocation. Each section addresses a specific failure mode and the concrete steps to prevent it.

Why API Key Management Best Practices Matter More Than You Think

API keys are bearer tokens. Anyone who possesses the key can act as the authorized entity. Unlike passwords, there is no second factor. Unlike OAuth tokens, most API keys do not expire automatically. Unlike session cookies, they are not scoped to a browser.

This combination makes API keys uniquely dangerous when mishandled:

  • Lateral movement: A leaked Stripe key does not just expose payment data — it can be used to issue refunds, modify subscriptions, or exfiltrate customer records.
  • Cost exposure: A compromised AWS key can spin up GPU instances for cryptocurrency mining. One startup received a $45,000 bill overnight from a single leaked key.
  • Supply chain risk: If your key provides write access to a package registry or CI/CD pipeline, an attacker can inject malicious code into your software supply chain.

The risks of sharing API keys in plain text extend beyond the initial exposure. Keys pasted into chat logs, emails, and tickets persist in those systems indefinitely — surviving long after the conversation ends.

How to Store API Keys Securely

The first rule: API keys do not belong in source code. Not in configuration files committed to Git. Not in environment variables defined in Dockerfiles. Not in CI/CD pipeline YAML checked into the repository.

Use a Secrets Manager

Dedicated secrets management services store credentials encrypted at rest and provide fine-grained access control:

ApproachEncryption at RestAccess ControlRotation SupportAudit Logging
Cloud Secrets Manager (AWS, GCP, Azure)✅ AES-256✅ IAM policies✅ Built-in✅ Full
HashiCorp Vault✅ AES-256-GCM✅ Policy-based✅ Dynamic secrets✅ Full
Environment Variables (server-level)❌ Plaintext on disk⚠️ OS-level only❌ Manual❌ None
.env Files (committed)❌ Plaintext in Git❌ Anyone with repo access❌ Manual❌ None
Hardcoded in Source❌ Plaintext in Git❌ Anyone with repo access❌ Manual❌ None

For teams that cannot justify the operational overhead of Vault, cloud-native options like AWS Secrets Manager ($0.40 per secret per month) or Google Cloud Secret Manager (free tier for six secrets) provide a solid baseline.

Separate Secrets From Configuration

Your application should load secrets at runtime, never at build time. A practical pattern:

# Bad: secret baked into the image
ENV STRIPE_KEY=sk_live_abc123

# Good: secret injected at runtime
ENV STRIPE_KEY_PATH=/run/secrets/stripe_key

This distinction matters because container images are cached, shared across registries, and persisted in CI artifacts. A secret in an image layer is a secret in every system that pulls that image.

Use .gitignore Correctly

Every repository should include .env and similar secret-bearing files in .gitignore before the first commit:

# .gitignore
.env
.env.local
.env.production
*.pem
*.key
credentials.json

Git’s history is append-only. If a secret reaches a commit — even if you delete it in the next commit — it remains in the history. Tools like git filter-branch or BFG Repo-Cleaner can rewrite history, but they require force-pushing to every clone. Prevention is drastically cheaper than remediation.

For a deeper look at secure environment file distribution within teams, see the guide on sharing .env files securely.

How to Build an API Key Rotation Strategy

Static credentials are a ticking clock. The longer a key exists, the greater the probability that it has been logged, cached, screenshotted, or copied to an insecure location. An effective api key rotation strategy limits this exposure window.

Define Rotation Intervals

Not all keys warrant the same rotation frequency. Base the interval on the blast radius of compromise:

  • Production payment keys (Stripe, Braintree): Rotate every 30 days. Financial exposure justifies the operational cost.
  • Cloud infrastructure keys (AWS, GCP): Rotate every 60-90 days, or use short-lived credentials via IAM roles and workload identity federation.
  • Third-party SaaS integrations (Slack, Twilio): Rotate every 90 days. Monitor for anomalous usage patterns between rotations.
  • Internal service-to-service keys: Rotate every 90-180 days, or implement mutual TLS to eliminate static keys entirely.

Automate Rotation

Manual rotation does not scale. A team managing 30 services with 5 API keys each faces 150 rotation events per cycle. Without automation, keys accumulate “rotation debt” — and the oldest, most dangerous keys are always the ones nobody wants to touch.

AWS Secrets Manager, HashiCorp Vault, and Doppler all support automated rotation. The pattern is consistent:

  1. Generate a new key via the provider’s API
  2. Update the secrets manager with the new value
  3. Deploy the new key to running services (rolling restart or hot-reload)
  4. Verify service health with the new key
  5. Revoke the old key after a grace period (typically 24-48 hours for in-flight requests)

Support Dual-Key Windows

Most API providers allow multiple active keys simultaneously. Use this feature during rotation to prevent downtime:

  1. Generate key B while key A is still active
  2. Deploy key B to all services
  3. Monitor for errors
  4. Revoke key A only after confirming zero traffic on it

This dual-key approach eliminates the zero-downtime rotation problem that discourages teams from rotating frequently.

API Key Security for Developers: Common Mistakes and How to Avoid Them

Knowing the theory is half the battle. The other half is recognizing where keys leak in real development workflows.

Mistake 1: Committing Keys to Version Control

GitHub scans over 200 token formats in public repositories through its secret scanning partnership program. In 2024, they detected and notified providers about millions of leaked credentials. But detection happens after the leak — the key is already in the commit history.

Fix: Use pre-commit hooks to scan for secrets before they reach the repository:

# Using gitleaks as a pre-commit hook
brew install gitleaks
gitleaks detect --source . --verbose

Tools like gitleaks, truffleHog, and detect-secrets catch keys, tokens, and high-entropy strings before they enter Git history.

Mistake 2: Sharing Keys Over Chat

Slack messages are searchable. Email is forwarded. Discord DMs are stored on servers you do not control. When you paste an API key into a chat window, you have created an unencrypted, unrevokable, indefinitely-persisted copy of that credential.

A 2023 survey by 1Password found that 61% of IT security professionals reported that employees routinely share credentials through insecure channels. The solution is not policy enforcement — it is providing a better alternative. When sharing credentials takes fewer steps than pasting into Slack, developers will use the secure path.

Read more about why you should stop sharing secrets in Slack and email.

Mistake 3: Over-Permissioned Keys

Most API providers offer scoped key creation. A key that only needs to read data should not have write access. A key that only accesses one endpoint should not authenticate against the entire API surface.

Apply the principle of least privilege:

  • ✅ Create separate keys for separate services
  • ✅ Use read-only keys where writes are not needed
  • ✅ Scope keys to specific IP ranges where the calling service has a static address
  • ✅ Set rate limits on keys to contain the blast radius of abuse
  • ❌ Do not create “god keys” with full administrative access for application use

Mistake 4: No Monitoring or Alerting

A key can be compromised for weeks before anyone notices — unless you are monitoring for anomalies. Set up alerts for:

  • API usage outside expected volumes (10x normal request rate)
  • Requests from unfamiliar IP addresses or geographic regions
  • Authentication failures followed by successful authentications (credential stuffing patterns)
  • Key usage during off-hours for services that should only run during business hours

How to Share API Keys Securely Across Teams

Key management is not a solo activity. Developers join teams, leave teams, and collaborate across organizational boundaries. The sharing workflow is where most security models break down.

Establish a Credential Sharing Protocol

Document a standard operating procedure that every team member follows:

  1. Never share raw keys in any messaging platform, email, or ticket system
  2. Use encrypted, expiring links for one-time credential transfers
  3. Separate the link from the decryption password across different communication channels
  4. Set download limits so credentials are accessed exactly once
  5. Log every share event so you have an audit trail of who received which credential and when

For a comprehensive walkthrough of team-level credential distribution, the API key sharing best practices knowledge base article covers the full workflow.

Secure Onboarding and Offboarding

When a developer joins, they need access to credentials. When they leave, every credential they accessed should be rotated. This is non-negotiable — yet most teams skip the offboarding rotation because it is painful.

Reduce that pain by:

  • Maintaining an inventory of which credentials each team member has accessed
  • Using short-lived credentials wherever possible (AWS STS temporary tokens, GCP workload identity)
  • Automating offboarding rotation as part of your HR/IT deprovisioning checklist
  • Scoping access so each developer only sees the secrets relevant to their work

API Key Lifecycle Checklist

Use this checklist to audit your current key management practices:

  • Generation: Keys are generated through the provider’s API or dashboard — never derived from predictable patterns
  • Storage: All production keys are stored in a secrets manager — not in source code, environment files, or configuration repositories
  • Access control: Each key is scoped to the minimum permissions required for its function
  • Rotation schedule: Every key has a defined rotation interval appropriate to its risk level
  • Automated rotation: Rotation is automated for all keys where the provider supports it
  • Sharing protocol: Credentials are shared via encrypted, expiring channels — never pasted into chat or email
  • Monitoring: API usage is monitored for anomalies, with alerts configured for suspicious patterns
  • Offboarding: All credentials accessed by departing team members are rotated within 24 hours
  • Incident response: A documented runbook exists for responding to key exposure events
  • Audit logging: Every key creation, rotation, access, and revocation event is logged

If you checked fewer than seven items, your key management posture has meaningful gaps that warrant immediate attention.

Start Managing API Keys the Right Way

API key management best practices boil down to three principles: minimize exposure, automate the tedious parts, and make the secure path the easiest path. When rotating keys requires a script instead of a sprint, and sharing credentials takes one click instead of a Slack paste, security becomes a default rather than an afterthought.

SecretDrop provides zero-knowledge encrypted sharing with expiring links, download limits, and no account required for recipients — purpose-built for the credential sharing workflows described in this guide. Upload a key, set an expiration, and share the link. The recipient opens it, enters the password, and the credential is decrypted locally in their browser. The server never sees the plaintext.

Get started with SecretDrop and replace insecure credential sharing with encrypted, auditable, self-destructing transfers.