コンテンツにスキップ

ランタイム設定

警告

アプリケーションにランタイム設定を追加するには、`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