ランタイム設定

警告: この機能はレガシーと見なされており、自動静的最適化 (Automatic Static Optimization)出力ファイルトレーシング (Output File Tracing)Reactサーバーコンポーネント (React Server Components) と互換性がありません。初期化のオーバーヘッドを避けるため、代わりに環境変数 (environment variables) を使用してください。

アプリケーションにランタイム設定を追加するには、next.config.jsを開き、publicRuntimeConfigserverRuntimeConfigを追加します:

next.config.js
module.exports = {
  serverRuntimeConfig: {
    // サーバーサイドでのみ利用可能
    mySecret: 'secret',
    secondSecret: process.env.SECOND_SECRET, // 環境変数から渡す
  },
  publicRuntimeConfig: {
    // サーバーとクライアントの両方で利用可能
    staticFolder: '/static',
  },
}

サーバー専用のランタイム設定はserverRuntimeConfigの下に配置してください。

クライアントとサーバーサイドのコードの両方からアクセス可能なものはpublicRuntimeConfigの下に配置します。

publicRuntimeConfigに依存するページでは、必ずgetInitialPropsまたはgetServerSidePropsを使用するか、自動静的最適化 (Automatic Static Optimization)を無効にするためにカスタムApp (Custom App)getInitialPropsを実装する必要があります。サーバーサイドレンダリング (SSR) されていないページ(またはページ内のコンポーネント)にはランタイム設定は利用できません。

アプリケーション内でランタイム設定にアクセスするには、以下のように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