Environment Variables

How to include environment variables in your Asserted test at runtime

It's likely that at some point you'll need to include some sensitive information like test tokens or usernames in your Asserted tests. Follow the instructions below to do so securely without saving these values directly in your git repo.

Included in the fixed dependencies is dotenv and getenv. These are simple libraries that are commonly used to pull in secrets or configuration from environment variables.

  • dotenv loads environment variables from an .env file into process.env

  • getenv reads the variables out of process.env and throws if they are missing rather than defaulting to an empty variable

If you plan on publishing to NPM it is extremely important that you exclude your .asserted directory if you have included a .env file in it.

Use the "files" property of your root package.json to include only the files and folders you want when publishing to NPM.

Storing Environment Variables

To access environment variables at runtime in Asserted, while still not checking them into your repo, do the following:

  1. Create a .env file containing the variables within the .asserted/ directory of your project

  2. Ensure that the .gitignore file inside the .asserted/ directory includes a reference to the .env file you just added (it should by default)

  3. Add an entry to the package.json in your .asserted/ directory for "files": [ "**/*.js", ".env" ], this will include the .env file in your package when you run asrtd push

  4. If your root package is going to be published to NPM, exclude .asserted from being published

After doing the above, when you run asrtd push, you should see the .env file listed in the files includes in the routine package, while still omitting the file from your git repo.

Reading Environment Variables

Populate process.env from the variables stored in the .env file using the following:

const path = require('path');

require('dotenv').config({ path: path.join(__dirname, './.env') });

It's best to use getenv to read whatever environment variables you're interested in, but you can just read directly from process.env if you prefer.

const getenv = require('getenv');

// Throws if process.env.TOKEN does not exist
const TOKEN = getenv('TOKEN');

// Works, but just silently defaults to undefined or an empty string if 
// the environment variable is not properly set
const TOKEN = process.env.TOKEN;

Last updated