运行时配置
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',
},
},
})
当把 apiBase
添加到 runtimeConfig.public
时,Nuxt 会把它加入到每个页面的 payload 中。我们可以在服务端和浏览器端通用地访问 apiBase
。
const runtimeConfig = useRuntimeConfig()
console.log(runtimeConfig.apiSecret)
console.log(runtimeConfig.public.apiBase)
公共运行时配置可以在 Vue 模板中通过
$config.public
访问。序列化
你的运行时配置会在传递给 Nitro 之前被序列化。这意味着任何不能被序列化然后反序列化的东西(例如函数、Set、Map 等)都不应当在你的 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
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 会尝试使用 unjs/untyped 从提供的运行时配置自动生成 TypeScript 接口。
但你也可以手动为运行时配置添加类型:
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
。