0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsで環境変数を参照できず,undefinedになることを解決した

0
Posted at

問題

Next.jsで環境変数を参照できず,undefinedになった.
原因,原因を見つけた方法を共有する.

原因

参照先を,Next.jsがクライアントサイドとして処理していた.

原因を見つけた方法

以下のコードのように,環境変数名の冒頭にNEXT_PUBLIC_をつけたところ,環境変数を参照できた.
つまり,参照先をNext.jsがクライアントサイドとして処理していたことになる.

.env.local
- API_KEY=HOGEHOGE
+ NEXT_PUBLIC_API_KEY=HOGEHOGE
src/app/api/test/test.ts
-     console.log(process.env.API_KEY);
+     console.log(process.env.NEXT_PUBLIC_API_KEY);

Next.jsではクライアントサイドから環境変数を参照する際には,環境変数名の冒頭にNEXT_PUBLIC_が付いている必要がある.

現状だと,参照した環境変数がブラウザ側から見えてしまうため,Next.jsがサーバーサイドとして処理するように修正する必要がある.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?