LoginSignup
37
12

More than 3 years have passed since last update.

Next.jsで環境変数を利用するためにdotenvは必要ない

Last updated at Posted at 2020-02-07

追記

環境変数についてRFCが出たので気長に待ちましょう。
よりセキュアに環境変数を設定することができます。
[RFC] .env environment support · Discussion #11106 · zeit/next.js

さらに追記

Enable NEXT_PUBLIC_ env var support by timneutkens · Pull Request #12283 · zeit/next.js

Last part needed for #11106. This enables inlining of NEXT_PUBLIC_ prefixed environment variables at build time.

上のRFCの実装が完了しました。こちらの方法で環境変数を設定しましょう。

tl;dr

next.config.jsenvに任意の値を設定するだけ
dotenvを使いたい場合にはnext.config.jsdotenvを呼び出せばよい

解説

Next.jsはVersion 8からbuild-inで環境変数(Environment Variables)に対応しています。
Blog - Next.js 8 | Next.js
下記リンクを参考にすれば容易に設定できるでしょう。
Environment Variables - Documentation | Next.js

ただし既存のdotenvシステムを利用したいケースもあるかと思います。
本体レポジトリにdotenvを使用したexampleも存在しているので参照してみましょう。
next.js/examples/with-dotenv at v9.2.1 · zeit/next.js

next.config.js
require('dotenv').config()
module.exports = {
  env: {
    // Reference a variable that was defined in the .env file and make it available at Build Time
    TEST_VAR: process.env.TEST_VAR,
  },
}

特に難しいことはなくdotenvが公式で推奨しているようにconfigを実行するだけです。
motdotla/dotenv: Loads environment variables from .env for nodejs projects.

As early as possible in your application, require and configure dotenv.
require('dotenv').config()

dotenv-webpackは(通常)必要ない

昔の記事ではdotenv-webpackの使用が推奨されていることがあります。
これはbuild-inで対応していなかったVesion 8以前にexampleにて推奨されていた方法です。
現在でも動作はしますが推奨されていません。以下が該当のIssueとPRです。
The with-dotenv example does not seem to follow current Next.js conventions · Issue #9371 · zeit/next.js
Update dotenv example by francismarcus · Pull Request #9372 · zeit/next.js

Next.jsは内部でwebpackを用いてビルドを行っています。それをカスタマイズする方法です。
筆者はNext.jsにおいてwebpackのカスタマイズは最小限にするべきだと考えています。
今回のようなケースでは使う必要はないかと思われます。

Next.js 8以降でdotenv-webpackを利用するケースが思いつかないのでよかったらコメントください。

37
12
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
37
12