Keeping a .env file out of version control seems useful, but a build can still put its contents into code sent to users. What checks and safeguards help prevent that?
How do you keep API keys out of front-end builds?
Answers
Treat anything shipped to the browser as public. A gitignored .env file can still feed a VITE_ variable into the JavaScript bundle, and the same general problem applies to secrets used in Next.js client components.
Keep privileged API calls on a server and have the client call that server instead. Check the framework's rules for which environment variables are exposed to client code. Moving secrets into an external store won't help if the build then injects them into the output.
Reply to this answer
Scan the final artifacts before deployment, not just the repository. Bundles and container images can contain secrets injected during a build even when the source scan is clean.
That's another layer, not a replacement for pre-commit checks, push protection, and reviewing config files. A scan also shouldn't be treated as proof that an artifact is safe.
Reply to this answer
Limit the damage too. Set a hard spending cap where the provider supports it, and use alerts as an early warning rather than assuming they'll stop charges. Remove unused keys and keep track of which services and tools hold the active ones.
Reply to this answer
If a key reaches a bundle or a config file that others could access, revoke or rotate it. Deleting the file or rewriting the repository history doesn't make the old key safe again.
Also consider where else credentials are stored. Third-party tools, backups, and account access can expose keys even when the application repository is clean.
Reply to this answer
Add your answer
Answers are reviewed before publication.
8v~skindle_527:
Scanning the output is especially useful when build tooling pulls in files or variables that aren't obvious from a source review.