For applications running on a server, environment variables offer a useful place to store configuration and secrets. Is it possible to use environment variables in apps that run in a browser?
It's useful to address this question across three chronological points in time:
- Build-time is when you (optionally) compile your JS bundle. The build process occurs on your machine or perhaps some CI server like Jenkins, and at this moment if your code references environment variables, they will be interpolated and baked into the output bundle. You won't be able to override the values after this point without serious shenanigans. Example: you set an environment variable locally,
export API_HOST="api.dogs.com", and run
npm run build. The line
const x = process.env.API_HOSTin your source becomes
const x = "api.dogs.com"in the bundle.
- Serve-time is when one or more servers serve your bundle from the previous step, along with any other files comprising your application, to a browser. "Serve-time" is not a common phrase, I just made it up. As a server process, here too environment variables are available somewhere, but it is possible that you don't have access to them if you're using a cloud provider and/or CDN where you just upload static assets that are served up without your further involvement (for example, S3 or Netlify). Even if you have access to this server process's environment variables, it might not be clear what you would do with them at this point regarding the single-page app because your bundle is already "done." But if you have the access you can read environment variables at this moment and in some fashion pass those values, or derivative values, along to the browser.
So yes, it's possible to use environment variables in the broader context of single-page apps, but not within the browser at runtime.
Subscribe to receive my latest posts in your inbox.