Stack Exchange
PM2 launching on wrong port for NextJS app
I have package.json scripts as follows:
"scripts": {
  "build": "NODE_ENV=production next build",
  "startLocal": "NODE_ENV=production node server.js",
  "startServer": "NODE_ENV=production pm2 start server.js",
}

Now, my app uses NextJS with a custom Express server. server.js looks a bit like this:
const { parse } = require('url');
const express = require('express');
const next = require('next');

const env = process.env.NODE_ENV || 'development';
const port = parseInt(process.env.PORT, 10) || 3000;
const app = next({ dev: env === 'development' });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get('*', (req, res) => {
    handle(req, res, parse(req.url, true));
  });

  server.listen(port, (err) => {
    if (err) throw err;
    console.info(`> Ready on port ${port}`);
  });
});

To build my app, I first run npm run build. Then I launch the app on a specific port number PORT=3030 npm run startLocal. This works as expected. However, when I use the script for a PM2 launch PORT=3030 npm run startServer it doesn't pick up the port number and launches on port 3000.
Why is this? Is there something else I need to add to the PM2 command in my package.json script?

pm2 only understand the environment variable NODE_PORT(not PORT) so i think you need to use PORT=3030 NODE_PORT=3030 npm run startServer so you it passes to both next and pm2.

What about a different variable like API_KEY?

if i understand you properly, you can add as much as you need of environment variable before the execution of a script(and that's what you are doing by npm run startServer) so you can add API_KEY=XXXX PORT=3030 NODE_PORT=3030 npm run startServer
