nuxt.js

Nuxt, .env and plain .js files


This relates to an app running Nuxt 3.12.4. I need to set a variable in a .env file, but that variable is needed in a plain .js file within the application's /lib. This, in nuxt.config.js, should make the variable available in .vue files:

 publicRuntimeConfig: {
    baseURL: process.env.BASE_URL
  },

But, it's still undefined in the .js file if I look for it with process.env and the application hangs if I try this.$config. I tried installing dotenv and doing:

require('dotenv').config();

In the relevant .js file, but still no luck. The next thing I'd look for is an index.js in which to require dotenv, but that file seems to be automatically generated.

Any ideas on how I might make this work?

The purpose, BTW, is to have a different URL when running on development hosts vs. production.


Solution

  • The only workaround I could find was to produce an env.js file containing:

    export function baseURL() {
        return 'http://localhost:5000/api'
    }
    

    Then, the plain Javascript (not vue/nuxt) file can have this:

    let BASE_URL;
    try {
        const env = require('../../env.js');
        BASE_URL = env.baseURL() || 'https://default/api';
    }
    catch {
        BASE_URL = 'https://default/api';
    }
    Object.freeze(BASE_URL);
    

    This achieves the goal of allowing developers to run the application on their laptops with a correct localhost URL without having to modify the lib/restApiLibrary.js file in question each time they do some work.