Loading…
Loading documentation...
Keep API keys and passwords out of the repository, the browser bundle, the logs and container images, and change one without a request failing.
Commands checked on 2026-10-27 with Next.js 16, Node.js 24, Ubuntu 24.04, Docker 29, gitleaks 8.29.
Your app reads its secrets from its environment, filled from a file that only root can read. The repository, the JavaScript sent to visitors, the logs and your container images hold none of them, and you have checked each one. You also know how to replace a secret so that no request is refused, on the old value or the new one.
~/nextapp, the service nextapp.YOUR_API_KEY stands for a real secret your server code uses, such as a payment provider's key.create-next-app makes one only when Git knows your name, which a new server does not, so git -C ~/nextapp log --oneline -1 may answer not a git repository. In that case make one, with your own name and email:cd ~/nextapp
git config --global user.name "Your Name"
git config --global user.email you@example.com
git init -b main
git add -A
git commit -q -m "First commit"
Next.js reads secrets for your own machine from .env.local. A new Next.js app's .gitignore already ignores every .env file; check that yours does before you put anything in one.
cd ~/nextapp
printf 'API_KEY=dev-only-value\n' > .env.local
git check-ignore -v .env.local
The answer names the rule that ignores the file, such as .gitignore:34:.env* .env.local. If it prints nothing, add the line .env* to .gitignore and run the check again.
A secret that was committed once stays in every copy of the repository after you delete the file. gitleaks reads every commit and reports what looks like a key, a token or a password; --redact keeps the values themselves out of its report.
docker run --rm -v "$PWD:/repo" ghcr.io/gitleaks/gitleaks:v8.29.1 git /repo --redact -v
On a clean repository it ends with no leaks found, after a line that counts what it read, such as 12 commits scanned.. Read that line too: 0 commits scanned. followed by no leaks found means it read nothing at all, because the folder is not the top of a Git repository. When it finds a secret, treat it as public: replace it at the service that issued it first (step 6), then take it out of the code. Rewriting the history afterwards does not take it back from anyone who already has a copy.
Next.js copies the value of every variable whose name starts with NEXT_PUBLIC_ into the JavaScript it sends to visitors, at build time. Any other variable stays on the server. So a secret never gets that prefix, and you can check a build for it: search the files sent to the browser for the value.
npm run build
grep -rlF 'dev-only-value' .next/static || echo 'not in the browser bundle'
not in the browser bundle is the answer you want. A file name instead means the value reaches every visitor; find the NEXT_PUBLIC_ variable or the client component that carries it.
systemd reads an EnvironmentFile= as root, before it starts the app as its own user, so the file can be closed to everyone else. Values written in the unit with Environment= are different: any user on the server can read them with systemctl show.
sudo install -d -m 755 /etc/nextapp
sudo install -m 600 -o root -g root /dev/null /etc/nextapp/env
printf 'API_KEY=%s\n' 'YOUR_API_KEY' | sudo tee /etc/nextapp/env > /dev/null
sudo mkdir -p /etc/systemd/system/nextapp.service.d
printf '[Service]\nEnvironmentFile=/etc/nextapp/env\n' | sudo tee /etc/systemd/system/nextapp.service.d/secrets.conf > /dev/null
sudo systemctl daemon-reload
sudo systemctl restart nextapp
A line that starts with a space is left out of the shell's history, so type the printf line with a space in front of it, or edit the file with sudoedit /etc/nextapp/env instead.
Check what each user can see:
sudo -u nextapp cat /etc/nextapp/env || true
systemctl show nextapp -p Environment
sudo cat /proc/$(systemctl show nextapp -p MainPID --value)/environ | tr '\0' '\n' | grep -c '^API_KEY='
The app's own user gets Permission denied. systemctl show lists only the Environment= lines, without the key. The running app has one API_KEY in its environment, which is where your code reads it with process.env.API_KEY.
Anything a Dockerfile passes with ARG or ENV is written into the image's history, and anyone who can pull the image can read it. A BuildKit secret mount gives one RUN step a file that is never stored. This build uses both, so you can see the difference:
mkdir -p ~/secret-demo && cd ~/secret-demo
printf 'demo-value-not-a-real-key\n' > token.txt
cat > Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM alpine:3.24
ARG LEAKY_TOKEN
RUN echo "an ARG of ${#LEAKY_TOKEN} characters"
RUN --mount=type=secret,id=token,required=true sh -c 'test -s /run/secrets/token && echo "a secret mount, read once"'
EOF
docker build --build-arg LEAKY_TOKEN="$(cat token.txt)" --secret id=token,src=token.txt -t secret-demo .
docker history --no-trunc secret-demo | grep -c 'demo-value-not-a-real-key'
Docker warns during the build (SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data), and the count is 3: the ARG line and both RUN lines after it hold the value, because an ARG is part of every later step, even the one that uses the secret mount. The secret's own value appears nowhere. Use --mount=type=secret for anything a build needs, such as a private registry token, and drop the ARG. required=true makes the build stop when the secret is missing, instead of running the step without it. Remove the demo with docker rmi secret-demo.
A secret can be refused for two reasons during a change: the old value stops working before your app has the new one, or your app checks for the new value before the sender has it. Both are avoided with an overlap, when the old and the new value both work for a while.
For a key your app sends to another service, most services let two keys be valid at once. Create the new key there, put it in /etc/nextapp/env, restart the app, check that its calls succeed, and only then delete the old key at the service.
For a secret your app checks, such as the secret that signs incoming webhooks, accept the previous value next to the current one while senders move over:
cat > check-secret.mjs <<'EOF'
import { timingSafeEqual } from 'node:crypto';
function matches(given, expected) {
const a = Buffer.from(given);
const b = Buffer.from(expected);
return a.length === b.length && timingSafeEqual(a, b);
}
export function acceptedSecret(given) {
const accepted = [process.env.WEBHOOK_SECRET, process.env.WEBHOOK_SECRET_PREVIOUS].filter(Boolean);
return accepted.some((expected) => matches(given, expected));
}
console.log(acceptedSecret('new-value'), acceptedSecret('old-value'), acceptedSecret('wrong-value'));
EOF
WEBHOOK_SECRET=new-value WEBHOOK_SECRET_PREVIOUS=old-value node check-secret.mjs
WEBHOOK_SECRET=new-value node check-secret.mjs
The first run prints true true false: during the overlap both values pass. The second, after you remove WEBHOOK_SECRET_PREVIOUS, prints true false false. timingSafeEqual compares in a time that does not depend on how many characters match, so the answer cannot be guessed one character at a time.
The restart that loads a new value takes about a second for a single process, and connections that arrive in that second are refused. To avoid even that, run two copies of the app behind a proxy and restart them one at a time.
Run the three checks from the steps again after any change to how the app gets its secrets:
cd ~/nextapp
git check-ignore -q .env.local && echo 'env file ignored'
grep -rlF 'dev-only-value' .next/static || echo 'not in the browser bundle'
sudo -u nextapp cat /etc/nextapp/env 2>/dev/null || echo 'secret file closed to the app user'
All three lines print their message: env file ignored, not in the browser bundle and secret file closed to the app user.
undefined where the key should be. The variable did not reach it. Check the name in /etc/nextapp/env matches the code exactly, that the file has one NAME=value per line with no spaces around =, and that you ran sudo systemctl daemon-reload before the restart. The /proc check in step 4 shows what the app really received.process.env. Find it with sudo journalctl -u nextapp | grep -c 'A_KNOWN_PREFIX' using the first characters of the key, remove the line, and replace the key, because the logs may already be copied elsewhere.0 commits scanned. and no leaks found. It read nothing: the folder you ran it from is not the top of a Git repository, and it still exits with success. Run it from the folder that holds .git.secret token: not found. The id in --secret differs from the id in the RUN --mount line. Without required=true there is no such error: the step runs with no file in /run/secrets and fails, or works wrongly, further on.STRIPE_SECRET_KEY, not KEY2), so the one to replace is obvious.Every Servers Are Up virtual machine and container includes an integrated HTML5 browser-based SSH, RDP, and VNC console in your dashboard, default-off inbound firewall rules with per-IP allow-lists, and full programmatic control via REST API v1 and Model Context Protocol (MCP). Explore our Virtual Datacenter Plans or reach out to Servers Are Up Support.