Nuxt Pass Server Environment Variables (process.env) to Client

Feb 16, 2020

env configuration

Edit nuxt.config.js.

export default {  env: {    API_URL: process.env.API_URL  }}

NOTE: The environment variables set during build. Meaning if you change process.env.API_URL during runtime on the server side, the client's process.env.API_URL shall not be updated.

NOTE: Refer https://nuxtjs.org/api/configuration-env/

Vuex

One of the special power of Nuxt's Vuex is the state/data committed by the server is available to the client.

Edit store/index.js.

export const state = () => ({  env: {    RUNTIME_API_URL: null // process.env.RUNTIME_API_URL  }})export const mutations = {  runtimeApiUrl(state, value) {    state.env.RUNTIME_API_URL = value  }}export const actions = {  nuxtServerInit({ commit }) {    commit('runtimeApiUrl', process.env.RUNTIME_API_URL)  }}

I am using RUNTIME_API_URL as the base url for Axios, which need to be configured during runtime (not during build) for both server and client.

Edit plugins/axios.js.

NOTE: Need to include this in the plugins section of nuxt.config.js as well.

export default function ({ $axios, redirect, store }) {  if (store.state.env.RUNTIME_API_URL) {    process.env.RUNTIME_API_URL = store.state.env.RUNTIME_API_URL  }  $axios.setBaseURL(process.env.RUNTIME_API_URL || process.env.API_URL)}

nux-env

nuxt-env

This module allows you to read environment variables server side—at runtime—and inject them into your app, meaning your Nuxt bundle is decoupled from your environment variables.

As with the config.env option in Nuxt config, environment variables used in nuxt-env are exposed client side

I tried with the following outcome

  • For build-time environment variables, if works perfectly with the variable accessible in both client and server
  • For runtime environment variables, it is only accessible on the server but not on the client

NOTE: Maybe I am not doing it right

Below is my nuxt.config.js

export default {  ...  modules: [    ...    ['nuxt-env', {      keys: [        'API_URL',          // build-time        'RUNTIME_API_URL'   // runtime      ]    }]  ],  ...}

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