LoginSignup
13
7

More than 3 years have passed since last update.

Next.jsの環境変数でハマったのでメモ

Posted at

Next.jsアプリケーションをDocker化して、複数環境にデプロイする際の環境変数の扱いでハマったのでメモ。

tl; dr

  • Next.jsでは、build時と実行の両方で使用できる環境変数と実行のみ使用できる環境変数が別途定義できる

前提

  • Next.jsアプリケーションをDocker化してデプロイしている
  • 本番とステージング環境で同じDockerイメージを使っている(環境変数でapiの接続先を変更する)

next.config.jsはこちら


//next.config.js

module.exports = {
  env: {
    API_URL: process.env.API_URL || "https://stg.hogehoge.api.com",
  }
};

問題の概要

実行時に、環境変数を下記のように定義した。

API_URL=https://hogehoge.api.com

しかし、アプリケーションに読み込まれている環境変数は API_URLhttps://stg.hogehoge.api.com になっていた。

なぜか

next.config.js 内の env config はbuild timeの環境変数を定義する設定だったことが原因。
build時には環境変数を渡していなかったため、 process.env.API_URLundefinedになり
API_URL にはデフォルト値の https://stg.hogehoge.api.com が使われていた。


//next.config.js

module.exports = {
  env: {
    API_URL: process.env.API_URL || "https://stg.hogehoge.api.com", //←のデフォルト値が使われてしまっていた
  }
};

解決方法

実行時に環境変数を読み込める publicRuntimeConfig を使用すれば解決する。


//next.config.js

module.exports = {
  publicRuntimeConfig: {
    // Will be available on both server and client
    API_URL: process.env.API_URL || "https://stg.hogehoge.api.com",
  },
};

アプリケーション内で使い方


import getConfig from 'next/config'

// Only holds serverRuntimeConfig and publicRuntimeConfig
const { publicRuntimeConfig } = getConfig()

console.log(serverRuntimeConfig.API_URL)

注意

publicRuntimeConfig に依存するページは、 getInitialProps を使用して Automatic Static Optimization の対象から外す必要がある。

Automatic Static Optimizationとは

13
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
7