Nuxt Detect Environment

Feb 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.

❤️ 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.