Passing env variables from PM2 to my Nuxt 3 App

ghz 8months ago ⋅ 78 views

I am using PM2 with a ecosystem.config.js config file to start my app. I am trying to pass env variables to my Nuxt 3 app, but they don't seem to be accessible from my app. This is my ecosystem.config.js:

module.exports = {
  apps: [
    {
      name: 'frontend',
      exec_mode: 'cluster',
      instances: 'max',
      script: './frontend/server/index.mjs',
      env: {
        NODE_ENV: 'production',
        NUXT_HOST: '10.0.0.49',
        NUXT_PORT: '3500',
        NUXT_BASE_URL: 'http://10.0.0.49:3500',
      },
    },
  ],
};

What am I doing wrong? 🤔

pm2 env 1 shows that all my env vars are there. However, in my Nuxt 3 App they are undefined.

Answers

If you are using Nuxt 3, you need to access environment variables using import.meta.env. Here's how you can access them in your Nuxt 3 app:

const { NUXT_HOST, NUXT_PORT, NUXT_BASE_URL } = import.meta.env;

console.log(NUXT_HOST); // Output: 10.0.0.49
console.log(NUXT_PORT); // Output: 3500
console.log(NUXT_BASE_URL); // Output: http://10.0.0.49:3500

Make sure you are accessing these environment variables after the Nuxt app has initialized, for example, in your Vue components or other JavaScript files within your Nuxt app.

If you are still having issues, you can also try logging import.meta.env to see all available environment variables and their values. This can help you verify that the environment variables are indeed being passed correctly to your Nuxt app.