Quick Tip - Overwrite Database Settings with Environment Variables in Loopback 4

Loopback 4 quick tip. Set database connection settings programmatically with environment variables

Quick Tip - Overwrite Database Settings with Environment Variables in Loopback 4

Unlike older versions of Loopback, Loopback 4 does not have a way of setting different datasource settings based off the environment(dev, stage, prod). At first this may not look like a problem, but when the time comes to deploy your application, you'll have to go in and change your datasource.json file to match the production database settings.

This means that you now have to change the your datasource each time you want to deploy to production and then again when you want to develop locally. In Loopback 3, you could simple create different environments (dev, stage, prod) and the application would load the correct datasource settings. In Loopback 4, this is not an option. Another rick in having your connection settings hardcoded is that you are saving your database username/password in your codebase.

The Solution

Thanks to how binding works in lb4, we can overwrite the values from our datasource.json file from within our application. In our application.ts file, add the following to the constructor, under the call to super.

    // Set datasource based off environment
    const db_host = process.env.MONGO_HOST || 'localhost';
    const db_port = process.env.MONGO_PORT || 27017;
    const db_user = process.env.MONGO_USERNAME || '';
    const db_pass = process.env.MONGO_PASSWORD || '';
    const database = process.env.MONGO_DB || 'todo-list';

      name: 'db',
      connector: 'mongodb',
      url: '',
      host: db_host,
      port: db_port,
      user: db_user,
      password: db_pass,
      database: database,
      useNewUrlParser: true,

First, we are assigning our database connection settings based of environment variables that are set. If the environment variable is not set, revert back to default values.

Next, we bind the datasource.config.db object to the variables we are assigning above.

Finally, we bind the datasources.db object to our DbDataSource object.

With this code in place, we can now control the connection settings to our MongoDB database based off environment variables. With a little help from a .env file in your project, you can now programmatically set your connection settings.

For more information on how binding works, and how we can use it to overwrite hardcoded values, check out Mikael von Ketelhodt's post where he talks about this in more detail. You can find his post here.

If you look inside our todo-list application on GitHub, you'll see that these changes have already been applied.