Nuxt Detect Environment

February 20, 2020
production, development, server, client, static

Production vs Development

You can check via process.env.NODE_ENV which usually have a value of production or development.

This variable is available at nuxt.config.js as well.

export default {
  axios: {
    port: process.env.NODE_ENV == 'production' ? 80 : 3000
  }
}

NOTE: You can load different dotenv based on NODE_ENV

Note that this is a build-time environment variable, not a runtime environment variable.

  • nuxt: process.env.NODE_ENV == 'development'
  • nuxt build: process.env.NODE_ENV == 'production'
  • nuxt generate: process.env.NODE_ENV == 'production'

Server, Client or Static

You can check for

  • process.server: Server (SSR)
  • process.client: Client (Browser JavaScript)
  • process.static: When you run nuxt generate. If you want to execute certain code on server (like reading a local file which is not available on the client), you need if (process.static && process.server).

Sadly, process.server/client/static is not available in nuxt.config.js. The way to go around this problem is to use plugins or some config which support function.

You can import specific library (only available for node/server environment. e.g. fs) or read local file / make http request depending on the environment.

if (process.static && process.server) {
  const fs = require('fs')
  const data = JSON.parse(fs.readFileSync(`static/data/config.json`, 'utf8'))
}
else {
  const { data } = await $axios.get(`/data/config.json`)
}

You specify specific plugins file to execute on specific environment only, or you can have a generic plugins file which check for process.server/client/static.

Edit nuxt.config.js.

export default {
  plugins: [
    '~/plugins/vue-notification', // both client and server
    { src: '~/plugins/vue-notification-client', mode: 'client' },
    { src: '~/plugins/vue-notification-server', mode: 'server' }
  ]
}

There is also a <client-only> tag for template.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.