﻿# PM2

> Use dotenvx with PM2

Find [code examples for this guide](https://github.com/dotenvx/examples/tree/main/process-managers/pm2) on GitHub.

## Initial setup

Generate an `ecosystem.config.js` file.

```console
$ pm2 init
```

Modify it to your needs. Something like this.

```javascript
module.exports = {
  apps : [{
    script: 'index.js',
    watch: '.'
  }]
};
```

Your `index.js` file should look something like this.

```javascript
// index.js
const PORT = process.env.PORT || 3000
const http = require('http')
const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end(`Hello ${process.env.HELLO}`)
});

server.listen(PORT, () => {
  console.log(`Server running on port:${PORT}/`);
});
```

## Run dotenvx

Add `@dotenvx/dotenvx` and `pm2` as dependencies.

```console
$ npm install @dotenvx/dotenvx --save
$ npm install pm2 --save
```

Then, in your `package.json`, modify your start script.

```json
{
  "scripts": {
    "start": "dotenvx run -- pm2-runtime start ecosystem.config.js --env production"
  },
  "dependencies": {
    "@dotenvx/dotenvx": "^3.0.0",
    "pm2": "^5.3.0"
  }
}
```

Create a `.env` file in the root of your project.

```dotenv
# .env
HELLO="World"
```

Inject your env using your start script — which is using dotenvx and pm2.

```console
$ npm start
```

Your app will say `Hello World`. That covers local development. Let's solve for production next.

## Add production environment

Create a `.env.production` file in the root of your project.

```dotenv
# .env.production
HELLO="production"
```

Modify your start script to load your `.env.production` file.

```json
{
  "scripts": {
    "start": "dotenvx run -f .env.production -- pm2-runtime start ecosystem.config.js --env production"
  },
  ...
}
```

Your app will say `Hello production`, simulating production.
