Environment variables

Variables that are isolated from the codebase.

We'll begin with our database credentials. First, create at the root of the project the file .env, which will hold our environment variables. Here, we can safely store the credentials.

DATASOURCE_USERNAME = postgres
DATASOURCE_PASSWORD = pass123
DATASOURCE_HOST = localhost
DATASOURCE_PORT = 5432
DATASOURCE_DATABASE = postgres

To make sure this file will never be published to the code repository, go to the file .gitignore and add it. You may notice that the file name in the file explorer will become grayed out.

# Env
*.env

Even though we have all those credentials, we can use just the URL to connect to the database, which can be created from them. For this reason, once again in .env, let's create the URL.

DATASOURCE_URL = postgresql://${DATASOURCE_USERNAME}:${DATASOURCE_PASSWORD}@${DATASOURCE_HOST}:${DATASOURCE_PORT}/${DATASOURCE_DATABASE}

As we have just created the .env file, we can already create the .env.example file too. It is a reflection of the .env but without the data, so that other developers may know the structure they must have in their own .env file.

DATASOURCE_USERNAME = ?
DATASOURCE_PASSWORD = ?
DATASOURCE_HOST = ?
DATASOURCE_PORT = ?
DATASOURCE_DATABASE = ?

DATASOURCE_URL = postgresql://${DATASOURCE_USERNAME}:${DATASOURCE_PASSWORD}@${DATASOURCE_HOST}:${DATASOURCE_PORT}/${DATASOURCE_DATABASE}

However, before we can begin using these variables, some issues need to be resolved, and that will be done in the next section.

Last updated