运行时配置

Nuxt 提供了一个运行时配置 API,用于在应用中公开配置和机密信息。

暴露

¥Exposing

要将配置和环境变量暴露给应用的其余部分,你需要在 nuxt.config 文件中使用 runtimeConfig 选项定义运行时配置。

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

nuxt.config.ts
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'
    }
  }
})

apiBase 添加到 runtimeConfig.public 时,Nuxt 会将其添加到每个页面的有效负载中。我们可以在服务器和浏览器中通用访问 apiBase

¥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)
在 Vue 模板中使用 $config.public 可以访问公共运行时配置。

序列化

¥Serialization

你的运行时配置将在传递给 Nitro 之前进行序列化。这意味着任何无法序列化和反序列化的内容(例如函数、Set、Map 等)都不应在 nuxt.config 中设置。

¥Your runtime config will be serialized before being passed to Nitro. This means that anything that cannot be serialized and then deserialized (such as functions, Sets, Maps, and so on), should not be set in your nuxt.config.

你可以将这些代码放在 Nuxt 或 Nitro 插件或中间件中,而不是将不可序列化的对象或函数从 nuxt.config 传递到你的应用中。

¥Instead of passing non-serializable objects or functions into your application from your nuxt.config, you can place this code in a Nuxt or Nitro plugin or middleware.

环境变量

¥Environment Variables

提供配置的最常用方法是使用 环境变量

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

Nuxi CLI 内置支持在开发、构建和生成过程中读取你的 .env 文件。但是当你运行构建的服务器时,your .env file will not be read。:read-more{to="/docs/guide/directory-structure/env"}

运行时配置值会在运行时自动替换为匹配的环境变量。

¥Runtime config values are automatically replaced by matching environment variables at runtime.

有两个关键要求:

¥There are two key requirements:

  1. 你所需的变量必须在 nuxt.config 中定义。这确保了任意环境变量不会暴露给你的应用代码。
  2. 只有特殊命名的环境变量才能覆盖运行时配置属性。也就是说,一个以 NUXT_ 开头的大写环境变量,使用 _ 分隔键和大小写变化。
runtimeConfig 的默认值设置为不同名称的环境变量(例如将 myVar 设置为 process.env.OTHER_VARIABLE)仅在构建时有效,并会在运行时中断。建议使用与 runtimeConfig 对象结构匹配的环境变量。¥Setting the default of runtimeConfig values to differently named environment variables (for example setting myVar to process.env.OTHER_VARIABLE) will only work during build-time and will break on runtime. It is advised to use environment variables that match the structure of your runtimeConfig object.
观看 Alexander Lichter 的视频,其中展示了开发者使用运行时配置时最常犯的错误。¥Watch a video from Alexander Lichter showcasing the top mistake developers make using runtimeConfig.

示例

¥Example

.env
NUXT_API_SECRET=api_secret_token
NUXT_PUBLIC_API_BASE=https://nuxtjs.org
nuxt.config.ts
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
    }
  },
})

阅读

¥Reading

Vue 应用

¥Vue App

在 Nuxt 应用的 Vue 部分中,你需要调用 useRuntimeConfig() 来访问运行时配置。

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

客户端和服务器端的行为有所不同:- 在客户端,只有 runtimeConfig.publicruntimeConfig.app(Nuxt 内部使用)中的键可用,并且该对象既可写又可响应。- 在服务器端,整个运行时配置都可用,但为了避免上下文共享,它是只读的。
pages/index.vue
<script setup lang="ts">
const config = useRuntimeConfig()

console.log('Runtime config:', config)
if (import.meta.server) {
  console.log('API secret:', config.apiSecret)
}
</script>

<template>
  <div>
    <div>Check developer console!</div>
  </div>
</template>
安全提示:注意不要通过渲染或将运行时配置密钥传递给 useState 来将密钥暴露给客户端。¥Security note: Be careful not to expose runtime config keys to the client-side by either rendering them or passing them to useState.

插件

¥Plugins

如果你想在任何(自定义)插件中使用运行时配置,则可以在 defineNuxtPlugin 函数中使用 useRuntimeConfig()

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

plugins/config.ts
export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()

  console.log('API base URL:', config.public.apiBase)
});

服务器路由

¥Server Routes

你也可以使用 useRuntimeConfig 在服务器路由中访问运行时配置。

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

server/api/test.ts
export default defineEventHandler(async (event) => {
  const { apiSecret } = useRuntimeConfig(event)
  const result = await $fetch('https://my.api.com/test', {
    headers: {
      Authorization: `Bearer ${apiSecret}`
    }
  })
  return result
})
全局路由中间件可以通过两种方式定义:

Typing 运行时配置

¥Typing Runtime Config

Nuxt 会尝试使用 unjs/untyped 根据提供的运行时配置自动生成 TypeScript 接口。

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

但你也可以手动输入运行时配置:

¥But it is also possible to type your runtime config manually:

index.d.ts
declare module 'nuxt/schema' {
  interface RuntimeConfig {
    apiSecret: string
  }
  interface PublicRuntimeConfig {
    apiBase: string
  }
}
// It is always important to ensure you import/export something when augmenting a type
export {}
nuxt/schema 是为了方便终端用户访问 Nuxt 在其项目中使用的架构版本而提供的。模块作者应该改为增强 @nuxt/schema