LoginSignup
2
2

More than 3 years have passed since last update.

Next.jsで環境変数を利用する

Posted at

とりあえずやり方教えて!

.envを用意します。

.env
TEST='HOGEEEEEE'

next.config.jsを編集します。ない場合はプロジェクトのルートディレクトリでvim next.config.jsして作ります。

next.config.js
module.exports = {
  env: {
    TEST: process.env.TEST
  }
}

indexかなんかで表示してみます。

index.tsx
export const Index = () => {
  const fuga = process.env.TEST;

  return (
    <p>{ fuga }</p>
  )
};

あとはyarn dev (OR npm run dev?)をして...

_人人人人人人_
> HOGEEEEEE <
 ̄Y^Y^Y^Y^Y^Y^ ̄

概要

環境

  • Fedora 31 Workstation
  • nodejs 13.14.0
  • yarn 1.22.4
  • next 9.4.4 ※9.4以上じゃないとできません
  • react 16.13.1
  • reac-dom 16.13.1

解説

参考元は公式ドキュメントです: https://nextjs.org/docs/basic-features/environment-variables

さて、Next.js 9.4から.env.local系の環境変数ファイルを読み込む、またブラウザに直接変数を読み込ませる機能を使うことができるようになりました。
後者については本題とずれるので割愛させていただきますので、詳細はドキュメントをお読みください。

これにより、例としてHeadコンポーネントを使用した、サイトタイトルの設定などがよくわからない設定を書かずに行えます。

また公式の文言によると、

Note: .env, .env.development, and .env.production files should be included in your repository as they define defaults. .env*.local should be added to .gitignore, as those files are intended to be ignored. .env.local is where secrets can be stored.

ようは、「.env.env.development.env.productionはリポジトリに含まれなければならない、そして.env*.local(末尾に.localがついているものですね)は.gitignoreによって除外されなければならない。」となっているので、基本的にはその運用になるかと思います。

また、

In general only one .env.local file is needed. However, sometimes you might want to add some defaults for the development (next dev) or production (next start) environment.

「next dev(yarn dev)では.env.development(.localも)、next startでは.env.production、が使われます」とあるので、こちらも有効活用しましょう。

参考

2
2
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
2
2