跳到主要內容
配置next.config.js 選項執行階段配置

執行階段配置

警告

若要將執行階段配置新增至您的應用程式,請開啟 next.config.js 並新增 publicRuntimeConfigserverRuntimeConfig 配置。

next.config.js
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 下。

任何客戶端和伺服器端程式碼皆可存取的內容應放在 publicRuntimeConfig 下。

依賴 publicRuntimeConfig 的頁面必須使用 getInitialPropsgetServerSideProps,或者您的應用程式必須具有帶有 getInitialProps自訂 App,才能選擇退出自動靜態最佳化。執行階段配置將無法用於任何未經伺服器端渲染的頁面(或頁面中的組件)。

若要在您的應用程式中存取執行階段配置,請使用 next/config,如下所示:

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