Using Environment Variables in Loopback
Last updated
Last updated
a loopback project
a connected database
In this section we are going to change the configuration of our Loopback app in order to deploy our application. Typically you will use different databases for production and development in our case we only have one, but we will go through the practice of setting up our application to work differently in production and development
The end goal will be an application that does not commit your secrets and api keys to git.
See Loopback Environment Configuration for more details.
Right now in your you loopback project in the server folder, your datasources.json should look something like this:
Your datasources.json file may looking slightly different
(1) What is wrong with this url? It has my username and password in it for the datatabase. username: john password: 1234
Our goal is to hide these values from git but still be able to use them when we are developing on our machine.
In your server folder create a file named datasources.local.js and paste the below code
Note this file is javascript instead of JSON like datasources.json
In the last section we created a file datasources.local.js
but still have our mongo database URL hardcoded into the file, see line 10. Now we are going to setup a an environment variable and try it out.
Loopback is just a NODE JS application, we are using NODE environment variables.
Your datasources.local.js should look something like below, but with your DB URL on line 7
Right now we have a working application but it is pretty tedious to remember that url or store that command. We could have multiple variables to set and the command would get quite large.
For example:
So in this step we want to use the .env
file that is not tracked by git to make this easier.
If your project does not have a .gitignore
file in your root directory, just create one. Otherwise you should be able to just open the file.
Line 6: add .env to the list
In order for NODE to use our .env
file we need to install the NPM package dotenv
Run the following command to install it.
Now open your datasources.local.js
and add line 1 to it from the below sample
Now restart loopback but do not use the environment variable in the command. Remember to run node . from root.
Your server is using the environment variable and connecting to the database if you see the following.
We created a new javascript file, datasources.local.js
to use when we start our app for local development. We then created a .env
file to store our environment variables and installed the npm package dotenv to allow the project to use this file to setup environment variables. Lastly we added the .env
to the .gitignore
file so our secrets are not in git. Now we need to prepare our app to use a different file for production, this was all for using local environment variables while we develop on our machine. In the next section we will launch our app to heroku using our a production config.