暴露配置到服务端和客户端

next/config模块使你应用运行时可以读取些存储在next.config.js的配置项。serverRuntimeConfig属性只在服务器端可用,publicRuntimeConfig属性在服务端和客户端可用。

  1. // next.config.js
  2. module.exports = {
  3. serverRuntimeConfig: { // Will only be available on the server side
  4. mySecret: 'secret'
  5. },
  6. publicRuntimeConfig: { // Will be available on both server and client
  7. staticFolder: '/static',
  8. mySecret: process.env.MY_SECRET // Pass through env variables
  9. }
  10. }
  1. // pages/index.js
  2. import getConfig from 'next/config'
  3. // Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else.
  4. const {serverRuntimeConfig, publicRuntimeConfig} = getConfig()
  5.  
  6. console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side
  7. console.log(publicRuntimeConfig.staticFolder) // Will be available on both server and client
  8.  
  9. export default () => <div>
  10. <img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
  11. </div>