Search code examples
node.jswebpackenvironment-variablespm2

Is there a way to pass PM2 cluster instance ID to a compiled webpack node.js server?


I'm trying to figure out, if there's a way to pass the PM2 cluster mode instance ID to a, compiled with webpack, node.js server. I want to write to different folders depending on the cluster id.

I've tried running the node server directly through PM2 and it can grab the instance_var (NODE_APP_INSTANCE) without any issues. I'm just not sure if there's some plugin or hack, that would allow the compiled app to accept/grab external env. variables.

Here's my webpack config, it's nothing special

const path = require('path');
const nodeExternals = require('webpack-node-externals');
const webpack = require('webpack');
const CopyPkgJsonPlugin = require('copy-pkg-json-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  node: {
    __dirname: false
  },
  output: {
    filename: 'testing.js',
    path: path.resolve(__dirname, 'dist/production')
  },
  target: 'node',
  externals: [nodeExternals()],
  plugins: [
    // new CopyPlugin([
    // { from: './ecosystem.config.js', to: path.resolve(__dirname, 'dist/production') }
    // ]),
    new CopyPkgJsonPlugin({
      remove: ['devDependencies']
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
        API_URL: JSON.stringify('127.0.0.1'),
        API_PORT: JSON.stringify('4000')
      }
    })
  ]
};

Most likely my approach is wrong, I'm open for suggestions.


Solution

  • Solved it by removing webpack.DefinePlugin

      new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: JSON.stringify('production'),
            API_URL: JSON.stringify('127.0.0.1'),
            API_PORT: JSON.stringify('4000')
          }
        })
    

    and passing the props from pm2 NODE_ENV=production API_URL=127.0.0.1 API_PORT=4000 pm2 start testing.js -i max

    Now the app has access to all env variables, including ones from PM2. Most likely it will also work with ecosystem.config.js file.