How to Inject Secrets at Runtime
Deliver secrets to an app at runtime instead of baking them in: load from a secret store, keep them out of images and env files, and rotate without rebuilds.
On this page
Introduction
A secret is anything that grants access: a database password, an API key, a signing key, a token. How a secret reaches the application matters because the delivery method determines where copies of it accumulate. Secrets baked into a container image end up in a registry, secrets checked into an env file end up in git history, and both outlive the change that put them there. Runtime injection keeps the artifact clean and the secret in one controlled place.
This tutorial covers keeping secrets out of artifacts, loading them from a store at runtime, refreshing for rotation without a rebuild, and redacting them from logs. The examples describe the delivery patterns and the accessor code, and the reasoning applies whether the store is a managed service, a mounted volume, or environment variables.
Keep secrets out of artifacts
The artifact is the image, the package, the repository, and any checked-in configuration. A secret in any of them is a secret with extra copies, and those copies are hard to revoke. Build images without secrets so the same image can run in every environment, and keep secrets out of the repository with a scan that fails the build when a high-entropy string or a known pattern appears.
An .env file checked in is the most common leak, because it is convenient during development and easy to forget. Keep a .env.example with the keys and no values, load the real values from outside the repository, and add a secret-scanner to CI and to pre-commit hooks so a real secret is caught before it enters history. Removing a secret from history after the fact is painful; preventing the commit is cheap.
# .env.example — keys only, no values, safe to commit
DATABASE_URL=
JWT_SIGNING_KEY=
STRIPE_API_KEY=
# developer loads real values from a secret store or an untracked .env.local
# CI has a secret scan that fails on a committed value
Load from a store at runtime
Fetch secrets at startup from a managed store or from a volume the platform injects, so the application reads them when it runs rather than when it is built. A managed store adds access control and audit: the application authenticates with its own identity, receives only the secrets it is allowed, and the read is logged. A mounted volume delivered by the platform is simpler and keeps the secret out of the image and out of environment listings.
Load into a dedicated secrets module that validates the required keys are present at startup, so a missing secret fails fast and loudly rather than at first use. Keep the values in memory and hand them out through accessors, not by exporting them everywhere, so you can later add refresh and redaction in one place. Validate and fail closed: an application that starts without its database password should not run in a degraded mode that hides the misconfiguration.
import { readFileSync } from 'node:fs';
function required(name, file) {
const value = process.env[name] ?? (file ? readFileSync(file, 'utf8').trim() : undefined);
if (!value) throw new Error('missing secret: ' + name);
return value;
}
export const secrets = Object.freeze({
databaseUrl: required('DATABASE_URL', '/run/secrets/database_url'),
signingKey: required('JWT_SIGNING_KEY', '/run/secrets/jwt_signing_key'),
});
Refresh and rotate without a rebuild
Reading a secret once at startup means a rotation requires a restart, which is often acceptable and simpler than dynamic reloading. Where a restart is disruptive, wrap the secret in an accessor that can refresh: watch the store or the file for a new version, and return the current value on read, so a rotation takes effect without a deploy. The accessor is the single place that knows how a secret is loaded and refreshed.
Support two active secrets during a rotation window. When rotating a signing key or an API key, both the old and the new must work until every consumer has moved, which is the same overlap principle as key rotation and API key rotation. A hard cutover, where the old secret stops working the instant the new is deployed, causes failures if any consumer is briefly behind.
class SecretRef {
private value: string;
constructor(initial: string, private reload: () => Promise<string>) {
this.value = initial;
}
get() { return this.value; }
async refresh() { this.value = await this.reload(); } // no restart needed
}
const signingKey = new SecretRef(secrets.signingKey, async () => readFromStore('jwt_signing_key'));
Redact secrets from logs and errors
A secret delivered correctly still leaks if it is logged. Object dumps, error messages that echo configuration, and request logging that includes an Authorization header all copy secrets into observability systems, which are often broader-access than the secret store. Configure the logger to redact known secret fields and header names, and never log an entire configuration object.
Redact by key name for structured logs and by pattern for free text. Mark secret-bearing fields so a serializer drops them, and scrub tokens and keys from error strings before they are emitted. Crash handlers and unhandled-exception reporters need the same treatment, because a stack or a request dump can carry a header or a config value. Redaction is part of secret handling, not an afterthought.
import pino from 'pino';
const logger = pino({
redact: {
paths: ['password', 'token', 'authorization', 'req.headers.authorization', 'req.headers.cookie'],
remove: true,
},
});
logger.info({ authorization: 'Bearer ' + signingKey }, 'loaded'); // value is dropped, not printed
Test that secrets stay out
Test that the built artifact contains no secret: inspect the image or the package for known secret patterns and assert none are present. Test that a missing required secret fails startup, so a misconfiguration is loud. Test that a log line emitted with a secret-bearing field does not contain the value, which proves the redaction. Test that a rotation updates the accessor value without a restart, if you implement refresh.
# fail if any secret pattern appears in the repo or image
grep -rE '(AKIA[0-9A-Z]{16}|sk_live_[0-9a-zA-Z]{24})' . && echo 'secret found' && exit 1
# a missing secret must stop startup
DATABASE_URL= node app.js 2>&1 | grep -q 'missing secret' && echo 'fails fast'
node -e 'const {logger}=require("./log"); logger.info({token:"x"}, "t");' | grep -q '"x"' && echo LEAK || echo redacted
Common pitfalls
Baking secrets into images, checking an .env with real values into git, reading a secret once and requiring a full redeploy for every rotation, a hard cutover that breaks consumers mid-rotation, and logging whole config objects or Authorization headers are the recurring mistakes. Runtime loading from a store, a validated secrets module, a refreshable accessor with overlap, and structured redaction address them.
Conclusion
Secrets belong in one controlled place, not in artifacts. Keep them out of images, packages, and repositories, load them from a store at runtime through a validated module, refresh for rotation with an overlap window, and redact them from logs and errors. Self-check by scanning the artifact for patterns, asserting startup fails on a missing secret, and confirming a logged secret field is dropped. Then a leaked artifact does not leak credentials, and a rotation is not a redeploy.
Sources: OWASP: Secrets management cheat sheet, HashiCorp Vault: Dynamic secrets, Kubernetes: Secrets.
FAQ
- Are environment variables safe for secrets?
- They are common and better than files in the image, but they can leak through process listings, crash dumps, and child processes. Treat them as one delivery mechanism among several, keep them out of artifacts, and prefer a secret store with access control where you can.
- How do I rotate without downtime?
- Load the secret through an accessor that can refresh, and either watch the store for a new version or accept new credentials via a restart. Support two active secrets during a rotation window, as with API keys and signing keys, so both old and new work while consumers move.
Report a problem with this articleOpens a pre-filled issue on GitHub.