Nuxt/docs/content/2.guide/4.going-further/10.runtime-config.md
Yaël Guilloux dc47c64f14
docs: use nuxt 3 and website theme (#5479)
Co-authored-by: Daniel Roe <daniel@roe.dev>
Co-authored-by: Sébastien Chopin <seb@nuxtjs.com>
Co-authored-by: Pooya Parsa <pooya@pi0.io>
Co-authored-by: pooya parsa <pyapar@gmail.com>
Co-authored-by: Clément Ollivier <clement.o2p@gmail.com>
2022-10-06 11:15:30 +02:00

5.1 KiB

title description
Runtime Config Nuxt provides a runtime config API to expose configuration within your application.

Runtime Config

Nuxt provides a runtime config API to expose configuration within your application and server routes, with the ability to update it at runtime by setting environment variables.

Exposing Runtime Config

To expose config and environment variables to the rest of your app, you will need to define runtime configuration in your nuxt.config file, using the runtimeConfig option.

Example:

export default defineNuxtConfig({
  runtimeConfig: {
    // The private keys which are only available within server-side
    apiSecret: '123',
    // Keys within public, will be also exposed to the client-side
    public: {
      apiBase: '/api'
    }
  }
})

When adding apiBase to the runtimeConfig.public, Nuxt adds it to each page payload. We can universally access apiBase in both server and browser.

const runtimeConfig = useRuntimeConfig()

console.log(runtimeConfig.apiSecret)
console.log(runtimeConfig.public.apiBase)

Environment Variables

The most common way to provide configuration is by using Environment Variables.

::alert{type=info} Nuxt CLI has built-in dotenv support in development mode and when running nuxi build and nuxi generate.

In addition to any process environment variables, if you have a .env file in your project root directory, it will be automatically loaded at build, dev, and generate time, and any environment variables set there will be accessible within your nuxt.config file and modules.

When updating .env in development mode, the Nuxt instance is automatically restarted to apply new values to the process.env.

However, after your server is built, you are responsible for setting environment variables when you run the server. Your .env file will not be read at this point. How you do this is different for every environment. On a Linux server, you could pass the environment variables as arguments using the terminal DATABASE_HOST=mydatabaseconnectionstring node .output/server/index.mjs. Or you could source your env file using source .env && node .output/server/index.mjs.

Note that for a purely static site, it is not possible to set runtime configuration config after your project is prerendered. ::

Runtime config values are automatically replaced by matching environment variables at runtime. For this to work, you must have a fallback value (which can just be an empty string) defined in your nuxt.config.

Example:

NUXT_API_SECRET=api_secret_token
NUXT_PUBLIC_API_BASE=https://nuxtjs.org
export default defineNuxtConfig({
  runtimeConfig: {
    apiSecret: '', // can be overridden by NUXT_API_SECRET environment variable
    public: {
      apiBase: '', // can be overridden by NUXT_PUBLIC_API_BASE environment variable
    }
  },
})

Accessing Runtime Config

Vue App

Within the Vue part of your Nuxt app, you will need to call useRuntimeConfig() to access the runtime config.

Note: Behavior is different between the client-side and server-side:

  • On the client-side, only keys in public are available, and the object is both writable and reactive. The entire runtime config is available on the server-side, but it is read-only to avoid context sharing.
<template>
  <div>
    <div>Check developer console!</div>
  </div>
</template>

<script setup>
const config = useRuntimeConfig()
console.log('Runtime config:', config)
if (process.server) {
  console.log('API secret:', config.apiSecret)
}
</script>

🛑 Security note: Be careful not to expose runtime config keys to the client-side by either rendering them or passing them to useState.

::alert{icon=👉} useRuntimeConfig only works during setup or Lifecycle Hooks. ::

Plugins

If you want to use the runtime config within any (custom) plugin, you can use useRuntimeConfig() inside of your defineNuxtPlugin function.

For Example:

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()
  console.log('API base URL:', config.public.apiBase)
});

Server Routes

You can access runtime config within the server routes as well using useRuntimeConfig.

export default async () => {
  const result = await $fetch('https://my.api.com/test', {
    headers: {
      Authorization: `Bearer ${useRuntimeConfig().apiSecret}`
    }
  })
  return result
}

Manually Typing Runtime Config

Nuxt tries to automatically generate a typescript interface from provided runtime config using unjs/untyped.

It is also possible to type your runtime config manually:

declare module '@nuxt/schema' {
  interface RuntimeConfig {
    apiSecret: string
    public: {
      apiBase: string
    }
  }
}
// It is always important to ensure you import/export something when augmenting a type
export {}