Nuxt.js dotenv Configuraton for Development and Production

Feb 14, 2020

You could use @nuxtjs/dotenv for configure different environment variable for development and production.


npm install --save-dev @nuxtjs/dotenv

Create .env file.

Edit env.development.


Edit env.production.


Edit nuxt.config.js.

// this is required to ensure nuxt.config.js can access the process.env.VAR_NAME// require('dotenv').config()// require('dotenv').config({ path: '.env.development' }) // {path: `.env.${process.env.ENV_FILE}`}require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })export default {  // ..  buildModules: [    // this is required to ensure the rest of Nuxt.js can access the process.env.VAR_NAME    // '@nuxtjs/dotenv'    // ['@nuxtjs/dotenv', { filename: `.env.${process.env.ENV_FILE}` }]    ['@nuxtjs/dotenv', { filename: `.env.${process.env.NODE_ENV}` }]  ],  modules: [    // Doc:    '@nuxtjs/axios',  ],  /*  ** Axios module configuration  ** See  */  axios: {    port: process.env.AXIOS_PORT  },}

NOTE: If you run npm run dev / nuxt, process.env.NODE_ENV == 'development. If you run npm run build / nuxt build or npm run generate / nux generate, process.env.NODE_ENV == 'production.

NOTE: The environment variable which affects Nuxt.js configuration take affect during build, not runtime. So you cannot pass it environment variable during runtime and expect the configuration to change.

More Configurations

What if I want to have more configuration type besides development and production?

You can send in your own environment variable (instead of using process.env.NODE_ENV).

Edit package.json to send in environment variable via env.

{  ...  "scripts": {    "dev": "env ENV_FILE=dev nuxt",    "build-test": "env ENV_FILE=test nuxt build",    "build": "env ENV_FILE=release nuxt build",    ...  },  ...}

When you run npm run dev, process.env.ENV_FILE == 'dev'. Edit nuxt.config.js to use process.env.ENV_FILE for dotenv filename / filepath configuration.

Client Side

By default, the variable set by dotenv seems to be only accessible on server-side. To make it available at client side as well, use ['@nuxtjs/dotenv', { filename: .env.${process.env.NODE_ENV}, systemvars: true }].

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.