Nuxt Runtime Config Variable

Jul 25, 2021

Environment Variable is good for build time variable. Use runtimeConfig for runtime environment variable.

  • publicRuntimeConfig: accessible from both client and server using $config
  • privateRuntimeConfig: accessible from server only using $config

Edit nuxt.config.js

export default {  publicRuntimeConfig: {    DATA_SOURCE: process.env.DATA_SOURCE || 'json'  },}

You can pass process.env.DATA_SOURCE via npm package.json.

Edit package.json.

{  "scripts": {    "dev": "env DATA_SOURCE=local nuxt",    "build": "env DATA_SOURCE=firestore nuxt build",    "generate": "env DATA_SOURCE=local nuxt generate",  },}

Access config in code

<template>  <div>    Data Source: $config.DATA_SOURCE  </div></template><script>export default {  data() {    return {      dataSource: this.$config.DATA_SOURCE    }  }}</script>

Access config in plugins

export default async ({ app, store, $config }, inject) => {  console.log('DATA_SOURCE', $config.DATA_SOURCE)}

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