- Blog post • 3 min read
Guide to Environment Variables in Bun
- Published on
- Vlad Matsiiako
What is Bun again?
The best thing about Bun is its speed. It's way faster than both Node.js and Deno, which makes it pretty compelling for edge computing.
Since environment variables are very commonly used to store configurations and secrets in Bun, we decided to explore how to use environment variables in Bun.
Reading environment variables
Environment variables in Bun can be called in two equivalent ways:
- The traditional Node.js way
- The new Bun way
In addition, you can run
bun run env to show all the secrets in the current process.
Injecting environment variables
Depending on your use case, you might want to choose one of the following options:
1. Injecting secrets from a .env file
Unlike older Node.js version, .env files are supported natively – you do not need to download the
Environment variables will be pulled from the following files listed in the orger of increasing precedence:
.env.production, .env.development, .env.test (depending on value of NODE_ENV) ->
In other words, after adding a
.env file with the following secrets:
You will be able to read their values with the following code:
2. Injecting using a secret manager like Infisical
.env files could work well for individual developers with a small number of secrets and fairly simple infrastructure. However, when your team starts growing, code complexity increases, and you need to make sure the highest levels of security and compliance, you should consider a secret manager like Infisical.
To inject secrets locally in Bun apps, you can use Infisical's CLI:
infisical run -- bun run dev–> the latest version of your secrets will always be pulled automatically.
What are the benefits of using Infisical?
- None of the secrets are stored locally – secrets are end-to-end encrypted.
- Manage multiple environments in one location: local, staging, production, and more.
- You always have the latest version of your environment variables – no need to sync .env files with your teammates.
- You can integrate Infisical easily across your infrastructure and various 3rd-party tools (GitHub Actions, CircleCI, Docker, Kubernetes, etc.).
- Secrets are version-controlled with the ability of point-in-time recovery.
- Automatically prevent hardcoded secrets and scan for secret leaks.
You can learn more about this process as well as other great features on Infisical's website.