Bart Bergmans
Bart Bergmans

Reputation: 4121

What is the best way to load environment variables in your build

For a project I am working on I am setting up a BitBucket pipeline. Everything works great except for the environment vars. One of the usages of my env vars is the API_URL. I am loading the url by using process.env.API_URL. Locally this works great since it loads the .env file by using dotenv-webpack. However, in the pipeline I don't know what the best way is to load these vars. Should I add all the vars to Bitbucket and add export API_URL=$API_URL for every var in the pipeline file or are there better ways to load the vars?

Upvotes: 1

Views: 2424

Answers (2)

Sapna
Sapna

Reputation: 683

I think it depends on what you are using to serve your application & at build stage npm build creates a static artefacts with env values. So you can use nginx subfilter in case using nginx to replace the values with environment variable.

Also, you can set env as mentioned here - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/

Upvotes: 0

esimonov
esimonov

Reputation: 634

Workspace, Repository, and Deployment variables is the way to go. Which one you need depends on scope you'd like these variables to cover (naming is pretty self-explanatory: some variables shouldn't change their values across your entire account; others only make sense to a particular repository; finally, some values are specific to a deployment environment).

Just define the variables in the Bitbucket UI or using API, and refer to their values from bitbucket-pipelines.yml or any script that you invoke from it. You don't need to add any export statements. Here's a very good doc explaining the details - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/ - and User-defined variables section is particularly relevant to your question.

Alternatively, if you committed your .env file, you can simply export its contents all at once as per this StackOverflow answer.

Obviously, don't commit .env if it contains any sensitive values.

Upvotes: 2

Related Questions