运行时配置
Nuxt 提供了一个运行时配置 API,用于在应用程序中公开配置和密钥。
公开配置
要将配置和环境变量公开给应用程序的其他部分,你需要在 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',
},
},
})
当向 runtimeConfig.public 添加 apiBase 时,Nuxt 会将其添加到每个页面的负载(payload)中。我们可以在服务器和浏览器中通用地访问 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 文件将不会被读取。运行时配置值会在 运行时被匹配的环境变量自动替换。
有两个关键要求
- 你所需的环境变量必须在
nuxt.config中定义。这确保了任意环境变量不会被暴露给你的应用程序代码。 - 只有命名特殊的环境变量才能覆盖运行时配置属性。即以
NUXT_开头的大写环境变量,并使用_来分隔键和表示大小写变化。
将
runtimeConfig 的默认值设置为 不同名称的环境变量(例如将 myVar 设置为 process.env.OTHER_VARIABLE)仅在构建时有效,在运行时会失败。建议使用与 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.public和runtimeConfig.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
})
运行时配置的类型定义
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 在其项目中使用的架构版本。模块开发者应改为扩展 @nuxt/schema。