Nexus Void Research

API Keys, Secrets Management, Environment Variables, Secret Manager, CWE-798, Key Rotation, How-to

How to Store API Keys Securely (Dev, Production, Frontend, CI)

How to store API keys securely: .env in development, a secret manager in production, nothing in frontend code or Docker images, scoped keys and rotation.

To store API keys securely, keep them out of your code and your git history entirely. Load them at runtime from environment variables in development and from a secret manager (AWS Secrets Manager, Google Secret Manager, Azure Key Vault or HashiCorp Vault) in production, never ship secret keys to a browser or mobile app, give each key the least privilege it needs, and rotate it on a schedule and immediately after any leak.

Hardcoded credentials are common enough that MITRE tracks them as CWE-798, and the OWASP Secrets Management Cheat Sheet treats centralised storage and rotation as the baseline. This guide covers where to store API keys at each stage, from a laptop .env file to production, plus the frontend, CI, Docker and database cases that catch most teams out.

Where should you never store an API key?

Most leaks come from a short list of places. Avoid all of them:

Place

Why it leaks

Source code (const KEY = "sk_live_...")

Every clone, fork and backup has it, forever

A committed .env or config file

Same as source code, and easy to miss in review

Frontend JavaScript or a mobile app bundle

Anyone can read it in browser dev tools or by unpacking the app

Docker image ENV or ARG lines

Visible in the image layers and docker history

Logs, error messages and analytics

Copied into third-party systems you do not control

Chat, tickets and wikis

Searchable by everyone with access, and rarely cleaned up

If a key has already landed in one of these, rotate it first, then clean up. Our guide on removing secrets from git history walks through the cleanup. To find keys that are already in your code, see how to find hardcoded secrets in code.

Step 1: Use environment variables and a .env file in development

Read keys from the environment so the same code works everywhere and the key never appears in the repository. This is the config principle from The Twelve-Factor App.

Create a .env file for local development:

STRIPE_SECRET_KEY=sk_test_xxxxxxxx
OPENAI_API_KEY=sk-xxxxxxxx
STRIPE_SECRET_KEY=sk_test_xxxxxxxx
OPENAI_API_KEY=sk-xxxxxxxx
STRIPE_SECRET_KEY=sk_test_xxxxxxxx
OPENAI_API_KEY=sk-xxxxxxxx

Ignore it, and commit a template with placeholder values instead:

echo ".env" >> .gitignore
cp .env .env.example   # then replace every value with a placeholder
echo ".env" >> .gitignore
cp .env .env.example   # then replace every value with a placeholder
echo ".env" >> .gitignore
cp .env .env.example   # then replace every value with a placeholder

Node.js (20.6 or later can load the file natively):

node --env-file=.env server.js
node --env-file=.env server.js
node --env-file=.env server.js
const stripeKey = process.env.STRIPE_SECRET_KEY;
if (stripeKey === undefined) throw new Error("STRIPE_SECRET_KEY is not set");
const stripeKey = process.env.STRIPE_SECRET_KEY;
if (stripeKey === undefined) throw new Error("STRIPE_SECRET_KEY is not set");
const stripeKey = process.env.STRIPE_SECRET_KEY;
if (stripeKey === undefined) throw new Error("STRIPE_SECRET_KEY is not set");

Python with python-dotenv:

import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.environ["OPENAI_API_KEY"]  # raises KeyError if missing
import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.environ["OPENAI_API_KEY"]  # raises KeyError if missing
import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.environ["OPENAI_API_KEY"]  # raises KeyError if missing

Fail fast when a key is missing, so a misconfigured deploy errors at startup instead of halfway through a request.

Step 2: Use a secret manager in production

.env files are fine on a laptop. In production, store keys in a secret manager and have the application or platform inject them at runtime:

Secret manager

Good fit

AWS Secrets Manager or SSM Parameter Store

Workloads on AWS

Google Secret Manager

Workloads on Google Cloud

Azure Key Vault

Workloads on Azure

HashiCorp Vault

Multi-cloud, on-premises, dynamic short-lived credentials

Your hosting platform's encrypted environment variables

Small apps on a PaaS

What a secret manager gives you that a file does not: encryption at rest, access control per service, an audit log of who read which secret, versioning, and rotation without a redeploy. Grant each service read access only to the secrets it uses.

Kubernetes note: a plain Kubernetes Secret is only base64-encoded. Turn on encryption at rest for etcd, restrict who can read Secrets with RBAC, or sync from an external secret manager.

Step 3: Never put secret keys in frontend code

Anything shipped to a browser or a mobile device is public. Build tools make this easy to get wrong, because some environment variables are copied into the client bundle by design:

  • Next.js exposes variables prefixed NEXT_PUBLIC_ to the browser.

  • Vite exposes variables prefixed VITE_.

  • Create React App embeds variables prefixed REACT_APP_ at build time.

Only put values in those that are meant to be public, such as a publishable key or a public analytics ID. For anything secret, call your own backend, and let the backend call the third-party API with the key it holds. Where a provider offers restricted keys, limit them by domain, IP address, app ID or API scope as a second layer.

Step 4: Keep keys out of CI/CD and Docker images

CI/CD. Store keys in your CI platform's encrypted secrets, reference them by name, and limit which branches and environments can use them. In GitHub Actions:

env:
  STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }}
env:
  STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }}
env:
  STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }}

For cloud access, prefer OpenID Connect (OIDC) federation over long-lived cloud keys, so the pipeline gets short-lived credentials per run. See how to secure a CI/CD pipeline with GitHub Actions.

Docker. Do not pass secrets with ENV or ARG, because they end up in the image. Use BuildKit secret mounts for build-time secrets, which are never written to a layer:

# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
docker build --secret id=npmrc,src=$HOME/.npmrc
docker build --secret id=npmrc,src=$HOME/.npmrc
docker build --secret id=npmrc,src=$HOME/.npmrc

Inject runtime secrets when the container starts, from your orchestrator or secret manager.

Step 5: Limit what each key can do

Assume every key will leak eventually, and limit the damage in advance:

  • Least privilege: use restricted or scoped keys that can only call the endpoints you need.

  • One key per environment and per service, so a leaked staging key cannot touch production and you can revoke one service without breaking the others.

  • Expiry: prefer short-lived tokens where the provider supports them.

  • Spend and rate limits on paid APIs, especially AI APIs, where a stolen key turns directly into a bill.

Step 6: Rotate keys on a schedule

Rotation turns a leak into a short incident instead of a long one. A rotation that does not break production looks like this:

  1. Create the new key alongside the old one.

  2. Update the secret manager, so services pick up the new key.

  3. Confirm traffic is using the new key.

  4. Revoke the old key.

  5. Check the provider's logs for any use of the old key after revocation.

Rotate on a fixed schedule, when someone with access leaves, and immediately after any suspected exposure.

Step 7: Store API keys you issue as hashes

If your product issues API keys to customers, treat them like passwords:

  • Generate them with a cryptographically secure random generator, with enough length (32 bytes or more) to make guessing impossible.

  • Show the full key once, at creation, then store only a hash of it, so a database leak does not leak working keys. Because the keys are long and random, a fast hash such as SHA-256 is acceptable here, unlike for human passwords.

  • Store a short visible prefix (for example ak_live_3f9c) so customers and support can identify a key without seeing it.

  • Support scopes, expiry, revocation and a last-used timestamp.

How does ARGUS help keep API keys out of your code?

ARGUS catches keys that slip into a repository and tells you which ones are dangerous right now.

  1. Three detection passes run on every repository scan: vendor-specific patterns, entropy analysis for random-looking strings, and named-assignment checks that catch a literal assigned to a variable such as api_key or client_secret.

  2. Noise filtering skips what usually buries the real finding: test and fixture paths, documentation placeholders, publishable keys, environment variable references, git SHAs and lockfiles.

  3. Live or not. With AI scanning on, each secret is marked Live, Rotated, Test or Unknown, so you rotate the live ones first.

  4. Pull request review runs secret detection on the changed lines of every pull request, and a gate policy such as block-reachable-secrets can fail a build that adds one.

Limits: ARGUS reports up to 60 secret findings per pass, skips files over 1 MB, and pull request review runs on GitHub. See ARGUS secret scanning, or scan a repository free.

Frequently asked questions

What is the most secure way to store API keys?

In a secret manager such as AWS Secrets Manager, Google Secret Manager, Azure Key Vault or HashiCorp Vault, injected into the application at runtime. That gives you encryption at rest, per-service access control, audit logs and rotation without code changes. Never store them in source code or client-side bundles.

Is it safe to store API keys in a .env file?

For local development, yes, as long as .env is in .gitignore and never committed. Commit a .env.example with placeholders instead. In production, use a secret manager or your platform's encrypted environment variables, because a file on disk has no access control, audit log or rotation.

How do I store API keys in environment variables?

Set them in your shell, a .env file loaded at startup, or your hosting platform's settings, then read them in code with process.env.NAME in Node.js or os.environ["NAME"] in Python. Check at startup that every required variable is set, and fail fast if one is missing.

How do I hide API keys in a React or Next.js app?

You cannot hide a secret in frontend code, because everything shipped to the browser is readable. Variables prefixed NEXT_PUBLIC_, VITE_ or REACT_APP_ are embedded in the bundle. Keep secret keys on your server, call your own backend route, and let the server call the third-party API.

Should API keys be stored in a database?

Only API keys you issue to your own customers, and only as hashes. Show the full key once, store a SHA-256 hash plus a short visible prefix, and support scopes, expiry and revocation. Third-party keys your app uses belong in a secret manager, not your application database.

How often should API keys be rotated?

On a regular schedule your team can sustain, such as every 90 days for high-privilege keys, whenever someone with access leaves, and immediately after any suspected leak. Create the new key first, switch traffic, then revoke the old one so rotation never causes downtime.

How do I pass API keys to a Docker container securely?

Inject them at runtime from your orchestrator or secret manager, not with ENV or ARG in the Dockerfile, which are stored in the image. For secrets needed at build time, use BuildKit secret mounts (RUN --mount=type=secret), which never write the secret into a layer.

What should I do if an API key is leaked?

Revoke it in the provider's console immediately, issue a new key and deploy it, then check the provider's logs for misuse. After that, remove the key from code and git history, and add secret scanning to pull requests so the next one is caught before it merges.

DATA SOURCES

OWASP Secrets Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html ; CWE-798: https://cwe.mitre.org/data/definitions/798.html ; Twelve-Factor App config: https://12factor.net/config

Liked this post? Share it: