Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass environment variable through PM2 to NextJS

I have 2 package.json scripts that look like this:

"start": "next start -p $PORT",
"pm2_staging": "pm2 restart ecosystem.config.js --env staging",

And an ecosystem.config.js that looks like this:

module.exports = {
  apps: [
    {
      name: 'test.co.uk',
      script: 'npm',
      args: 'start',
      env_staging: {
        API: 'staging',
        NODE_ENV: 'production',
        PORT: 3001,
      },
    },
  ],
};

I then run the following:

TEST_VAR='test' npm run pm2_staging

I would expect the following to happen:

  • The PM2 restart command fires
  • ecosystem.config.js fires the npm start command and sets some environment variables
  • The app starts and all env vars are available, including TEST_VAR (set in the original command)

What actually happens is all the env vars from the ecosystem are correctly set, but TEST_VAR is not available in the app. Why is this and how do I go about setting secret keys from CI tools if I can't do this?

like image 980
CaribouCode Avatar asked Nov 16 '22 21:11

CaribouCode


1 Answers

I ran into the same problem tonight. After looking every where I found the config needed. The env variable needs to go in your ecosystem.config.js like below. In my case I put it at the root of my server

  module.exports = {
  apps : [{
    name: 'nextjs',
    script: 'yarn',
    args:"start",
    cwd:"/var/www/myapp/",
    instances: 2,
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'development'
    },
    env_production: {
      NODE_ENV: 'production',
      API_URL: 'YOUR ENV URL',
      PORT:8000
    }
  }]
};

package.json like so

"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start -p 8000"
  },
...

and executed something like this

#!/bin/bash
cd /var/www/myapp/
git pull && yarn install && yarn build
cd ~/
pm2 start ecosystem.config.js --env production

Then the API_URL would be available in const API_URL = process.env.API_URL in your app. These urls helped https://willandskill.se/en/setup-a-next-js-project-with-pm2-nginx-and-yarn-on-ubuntu-18-04/ https://pm2.keymetrics.io/docs/usage/application-declaration/

like image 66
webface Avatar answered Dec 06 '22 11:12

webface