Skip to content

Usage of .env Files

KaiWissel edited this page Nov 26, 2021 · 20 revisions

Why

With .env-Files we have an easy way to provide configuration options from an external source.

Where

ENV-Vars are used by every docker container and the applications running inside them. ENV-Vars are also necessary for unit-test in the backend.

How to use

Docker compose

If you start up a docker-compose environemnt, docker will look in the root folder of that docker-compose-file for an .env-File and will load these vars into the environments of the container.

You can also specify a different .env-File with the flag --env-var docker-compose -f docker-compose-ci.yml --env-file ./.env.ci up -d

Backend Unit-Test

Some backend modules depend on a configuration via ENV-Vars. Therefore if you want to create a unit-test you have to provide these ENV-Vars.

To use ENV-VARS in the jest context you have to:

  • Add to package.json:
"jest": {
    "setupFiles": [
      "<rootDir>/test/setup-tests.js"
    ]
  },

If you use the following code jest will use the default .env

"jest": {
    "setupFiles": [
      "dotenv/config"
    ]
  }
  • Create file "setup-tests.js" where you can specify a particular .env-File
require("dotenv").config({ path: "./.env.ci" });
  • Add the following comment to the jest test file:
/**
 * @jest-environment node
 */

CI

To startup our E2E testing environment we also have to present ENV-Vars to the environemnt. Therefore a special .env.ci was created. This file is currently also used by the unit-tests.

Docker-Compose

To use it in CI you have to specify it when starting docker-compose (see above)

Backend / NodsJS

The backend (NodeJS) searches by default for a .env-File. To specify a different file you have to define it at the earliest possible moment in the root file of the backend (app.js)

if (process.env.NODE_ENV === "CI") {
  require("dotenv").config({ path: "./.env.ci" });
}
Clone this wiki locally