執行時期設定 (Runtime Config)
警告:
- 此功能已被棄用。 我們建議改用環境變數,該方式也支援讀取執行時期數值。
- 您可以使用
register
函式在伺服器啟動時執行程式碼。- 此功能無法與自動靜態優化 (Automatic Static Optimization)、輸出檔案追蹤 (Output File Tracing) 或 React 伺服器元件 (React Server Components) 一起使用。
若要為您的應用程式新增執行時期設定,請開啟 next.config.js
並新增 publicRuntimeConfig
與 serverRuntimeConfig
設定:
module.exports = {
serverRuntimeConfig: {
// 僅在伺服器端可用
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // 透過環境變數傳遞
},
publicRuntimeConfig: {
// 在伺服器端與客戶端皆可用
staticFolder: '/static',
},
}
將任何僅限伺服器使用的執行時期設定置於 serverRuntimeConfig
下。
任何客戶端與伺服器端程式碼皆可存取的內容應置於 publicRuntimeConfig
下。
依賴
publicRuntimeConfig
的頁面必須使用getInitialProps
或getServerSideProps
,或者您的應用程式必須擁有帶有getInitialProps
的自訂 App (Custom App) 以退出自動靜態優化 (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