Dotenv 101
Software that depends on third-party data sources will eventually encounter the need to handle sensitive information such as API credentials or tokens to authenticate. Making this information publicly available, for example, in GitHub, is not a great idea because it is easy to spin up a scraper bot that goes through public repositories looking for keywords, such as DB_USER
or DB_PASSWORD
.
Figure 1. Example of a scraper bot, GitMiner
We can handle these using environment variables. These are variables stored in your host system and are available to your application at any time. Dotenv makes this task simple by handling them in a single file.
How to use dotenv
To use dotenv for handling environment variables:
- Install dotev as with any npm package.
npm install dotenv
2. Import it into your project.
require('dotenv').config()
3. Create your secrets file. This example uses .env
as a name but you could use any name, and you could use any number of files.
PORT=8080 SECRET_API_KEY=eDdxpBq82tNhYD739CsX5r7mT
IMPORTANT: Don’t forget to add your .env
file to .gitignore
How to use spin up a quick express webserver
To spin up a quick express webserver to show how to use them on code:
- Use:
require('dotenv').config()
const express = require('express');
const server = express();
const port = process.env.PORT || 3000; // If env variable is undefined, it will fallback to 3000.
server.get('/', (req, res) => {
let payload = 'Your secret key is '+process.env.SECRET_API_KEY
res.send(payload);
})
server.listen(port, () => {
console.log('Server is running on port '+port)
})
2. Check your terminal:
Server is running in port 8080
3. Open your browser and go to localhost:8080
4. See our output is the variable we passed using dotenv!
This is just a straightforward example of what you can achieve using dotenv, but we encourage you to read the docs to see all features that you could use for your project.
Written by Uriel Coria, Software QA Engineer at Wizeline.