Home

Issue: 2998

Use environment variables inside nuxt.config.js

[issue link]

Hey!

Description

I’m currently trying to set several config parameters depending on whether nuxt.js is launched in dev or production mode. To accomplish this, I haven’t changed any environment variables before starting nuxt.
Unfortunately, the following won’t work (using the axios module) by default:

  /*
   * Axios
   */
  axios: {
    baseURL: process.env.NODE_ENV !== 'production' ? 'http://api.xyz.test' : 'https://api.xyz.com'
  },

If I use console.log(process.env.NODE_ENV) in the nuxt.config.js file, it’s undefined (if not set before)

Current possible solution

I only came up with one solution for it:

Set env variables before starting

We could update the package.json scripts to include NODE_ENV or set it manually through the console.
The former blocks “overriding” ENV through the command line, the latter is quite tedious.

"scripts": {
    "dev": "NODE_ENV=development nuxt",
    "build": "NODE_ENV=production nuxt build",
    "start": "NODE_ENV=production nuxt start",
    "generate": "NODE_ENV=production nuxt generate", 
  },

Use dotenv module

Also a way to deal with it, and highly customizable. Still, there should be an easier way to define the “default” configuration which would be enough in many use-cases.

Other solutions?

Are there better ways to accomplish similar behavior easier?

By default, NODE_ENV is set depending on the nuxt mode (nuxt dev = development, production otherwise), but I guess this happens after interpreting the config.

Could we use extend() for it? 🤔

Related

https://github.com/nuxt/nuxt.js/blob/dev/lib/builder/webpack/server.config.js#L50
https://github.com/nuxt/nuxt.js/issues/1386

This bug report is available on Nuxt.js community (#c2598)