运行时配置
警告:
¥Warning:
此功能已弃用。我们建议改用 环境变量,它也可以支持读取运行时值。
¥This feature is deprecated. We recommend using environment variables instead, which also can support reading runtime values.
你可以使用
register
功能.conf 在服务器启动时运行代码。¥You can run code on server startup using the
register
function.此功能不适用于 自动静态优化、输出文件跟踪 或 React 服务器组件。
¥This feature does not work with Automatic Static Optimization, Output File Tracing, or React Server Components.
要将运行时配置添加到你的应用,请打开 next.config.js
并添加 publicRuntimeConfig
和 serverRuntimeConfig
配置:
¥To add runtime configuration to your app, open next.config.js
and add the publicRuntimeConfig
and serverRuntimeConfig
configs:
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
将任何仅服务器运行时配置放在 serverRuntimeConfig
下。
¥Place any server-only runtime config under serverRuntimeConfig
.
客户端和服务器端代码均可访问的任何内容都应位于 publicRuntimeConfig
下。
¥Anything accessible to both client and server-side code should be under publicRuntimeConfig
.
依赖
publicRuntimeConfig
的页面必须使用getInitialProps
或getServerSideProps
,或者你的应用必须具有 自定义应用 和getInitialProps
才能选择退出 自动静态优化。如果没有服务器端渲染,运行时配置将不可用于任何页面(或页面中的组件)。¥A page that relies on
publicRuntimeConfig
must usegetInitialProps
orgetServerSideProps
or your application must have a Custom App withgetInitialProps
to opt-out of Automatic Static Optimization. Runtime configuration won't be available to any page (or component in a page) without being server-side rendered.
要访问应用中的运行时配置,请使用 next/config
,如下所示:
¥To get access to the runtime configs in your app use next/config
, like so:
import getConfig from 'next/config'
import Image from 'next/image'
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)
function MyImage() {
return (
<div>
<Image
src={`${publicRuntimeConfig.staticFolder}/logo.png`}
alt="logo"
layout="fill"
/>
</div>
)
}
export default MyImage