執行時期設定

警告:

若要為您的應用程式新增執行時期設定,請開啟 next.config.js 並新增 publicRuntimeConfigserverRuntimeConfig 設定:

next.config.js
module.exports = {
  serverRuntimeConfig: {
    // 僅在伺服器端可用
    mySecret: 'secret',
    secondSecret: process.env.SECOND_SECRET, // 透過環境變數傳遞
  },
  publicRuntimeConfig: {
    // 在伺服器端和客戶端皆可用
    staticFolder: '/static',
  },
}

將僅限伺服器端的執行時期設定置於 serverRuntimeConfig 下。

任何客戶端與伺服器端程式碼皆可存取的設定應置於 publicRuntimeConfig 下。

依賴 publicRuntimeConfig 的頁面必須使用 getInitialPropsgetServerSideProps,或者您的應用程式必須在自訂 App (Custom App) 中使用 getInitialProps 以退出自動靜態優化 (Automatic Static Optimization)。若未進行伺服器端渲染,任何頁面(或頁面中的元件)都無法使用執行時期設定。

要在應用程式中存取執行時期設定,請使用 next/config,如下所示:

import getConfig from 'next/config'
import Image from 'next/image'

// 僅包含 serverRuntimeConfig 和 publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// 僅在伺服器端可用
console.log(serverRuntimeConfig.mySecret)
// 在伺服器端和客戶端皆可用
console.log(publicRuntimeConfig.staticFolder)

function MyImage() {
  return (
    <div>
      <Image
        src={`${publicRuntimeConfig.staticFolder}/logo.png`}
        alt="logo"
        layout="fill"
      />
    </div>
  )
}

export default MyImage