ランタイム設定
警告
- この機能は非推奨です。 ランタイム値の読み取りもサポートできる環境変数の使用をお勧めします。
register
関数を使用して、サーバー起動時にコードを実行できます。- この機能は、自動静的最適化、出力ファイルのトレース、またはReact サーバーコンポーネントでは機能しません。
アプリケーションにランタイム設定を追加するには、`next.config.js` を開き、`publicRuntimeConfig` と `serverRuntimeConfig` 設定を追加します。
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` に依存するページは、`getInitialProps` または `getServerSideProps` を使用する**必要があります**。または、アプリケーションに `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
これは役に立ちましたか?