Node Js: Setting Environment Variables Using pm2 library
Table of contents
No headings in the article.
What is PM2?
pm2 is a process manager for Node.js applications. It allows you to keep your application running in the background on your server, even if you log out or close the terminal window.
pm2 provides several features for managing and monitoring your Node.js applications, including:
Automatic restarting of crashed or exited processes
Load balancing of multiple instances of an application
Logging and error reporting
Monitoring of application performance and resource usage
To use pm2, you first need to install it globally on your server using npm:
npm install -g pm2
Setting environment variables using pm2.
Normally when running node applications in the development we would use dotenv package to load environment variables by calling config on app initializations as follows.
const dotenv = require('dotenv');
dotenv.config();
There are several ways to load environment variables using the pm2 package as demonstrated below.
Setting Environment Variables in a json file.
This approach will negate the need to require or install dotenv package. Environment variables are set using json object as follows.
{
"apps": [
{
"name": "App1",
"script": "index.js",
"env": {
"APP_DESCRIPTION": "USING PM2 TO LOAD ENVIRONMENT VARIABLES"
}
}
]
}
With this approach, our index.js would look like this.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(process.env.APP_DESCRIPTION);
});
server.listen(port, hostname, () => {
console.log(process.env.APP_DESCRIPTION)
});
// starting the application
pm2 start app.json
Setting the Environment variable in the pm2 config file.
This approach requires the installation of the dotenv package. We import environment variables from .env files by setting require dotenv/config as a node argument as follows.
// .env
APP_DESCRIPTION=USING PM2 TO LOAD ENVIRONMENT VARIABLES
// pm2.config.js
module.exports = {
apps : [{
name : 'My Application',
script : 'index.js',
node_args : '-r dotenv/config',
}],
}
// index .js
require('dotenv').config();
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(process.env.APP_DESCRIPTION);
});
server.listen(port, hostname, () => {
console.log(process.env.APP_DESCRIPTION)
});
// starting the application
pm2 start pm2.config.js
Thats it. Happy coding!!