暴露配置到服务端和客户端
优质
小牛编辑
137浏览
2023-12-01
next/config
模块使你应用运行时可以读取些存储在next.config.js
的配置项。serverRuntimeConfig
属性只在服务器端可用,publicRuntimeConfig
属性在服务端和客户端可用。
// next.config.js
module.exports = {
serverRuntimeConfig: { // Will only be available on the server side
mySecret: 'secret'
},
publicRuntimeConfig: { // Will be available on both server and client
staticFolder: '/static',
mySecret: process.env.MY_SECRET // Pass through env variables
}
}
// pages/index.js
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else.
const {serverRuntimeConfig, publicRuntimeConfig} = getConfig()
console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side
console.log(publicRuntimeConfig.staticFolder) // Will be available on both server and client
export default () => <div>
<img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
</div>