运行时配置

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

公开

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

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

const runtimeConfig = useRuntimeConfig()

console.log(runtimeConfig.apiSecret)
console.log(runtimeConfig.public.apiBase)
在 Vue 模板中,可以使用 $config.public 访问公共运行时配置。

序列化

您的运行时配置将在传递给 Nitro 之前被序列化。这意味着任何不能被序列化然后再反序列化(如函数、Set、Map 等)的内容,都不应设置在您的 nuxt.config 中。

与其从 nuxt.config 中向应用程序传递不可序列化的对象或函数,不如将此代码放在 Nuxt 或 Nitro 插件或中间件中。

环境变量

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

Nuxt CLI 内置支持在开发、构建和生成期间读取您的 .env 文件。但是当您运行构建后的服务器时,将不会读取您的 .env 文件
文档 > 4.x > 目录结构 > 环境变量 中阅读更多内容。

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

有两个关键要求

  1. 您需要的变量必须在 nuxt.config 中定义。这确保了任意环境变量不会暴露给您的应用程序代码。
  2. 只有以特定名称命名的环境变量才能覆盖运行时配置属性。也就是说,一个以 NUXT_ 开头的大写环境变量,它使用 _ 来分隔键和大小写。
runtimeConfig 值的默认值设置为名称不同的环境变量(例如将 myVar 设置为 process.env.OTHER_VARIABLE)只在构建时有效,在运行时会中断。建议使用与 runtimeConfig 对象的结构匹配的环境变量。
观看 Alexander Lichter 的视频,了解开发人员在使用 runtimeConfig 时常犯的顶级错误。

示例

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

读取

Vue 应用

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

客户端和服务端的行为不同
  • 在客户端,只有 runtimeConfig.publicruntimeConfig.app(Nuxt 内部使用)中的键可用,并且该对象是可写和响应式的。
  • 在服务端,整个运行时配置都是可用的,但它是只读的,以避免上下文共享。
app/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 来将运行时配置键暴露给客户端。

插件

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

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

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

服务器路由

您也可以在服务器路由中使用 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
})
event 作为参数传递给 useRuntimeConfig 是可选的,但建议传递它,以便在运行时为服务器路由获取被环境变量覆盖的运行时配置。

键入运行时配置

Nuxt 尝试使用以下内容自动从提供的运行时配置生成 TypeScript 接口unjs/untyped.

但也可以手动为运行时配置添加类型

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 使用的 schema 版本。模块作者应改为增强 @nuxt/schema