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

【React/ Vite】`process.env.`を使おうとしたらちょっとだけハマった('process' is not defined.)

2
Last updated at Posted at 2026-07-16

はじめに

React x Vite の環境立ち上げて、環境変数の.env.local使おうとしたらちょっとだけハマったので残します。

問題

以下のようにsupabaseクライアントを作成して、各キーを.env.localに隠してprocess.env.を使用してそれぞれ読み込もうとしました。

lib/clients/supabase.js
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_PUBLISHABLE_KEY
)

すると、processあたりに以下のエラー警告が。

'process' is not defined.

processまわりって何かしないといけなかったっけ?

解決方法

eslint.config.jsに以下★の行を追加すればOK。

eslint.config.js
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import { defineConfig, globalIgnores } from 'eslint/config'

export default defineConfig([
  globalIgnores(['dist']),
  {
    files: ['**/*.{js,jsx}'],
    extends: [
      js.configs.recommended,
      reactHooks.configs.flat.recommended,
      reactRefresh.configs.vite,
    ],
    languageOptions: {
      globals: globals.browser,
      parserOptions: { ecmaFeatures: { jsx: true } },
    },
  },
  // ★以下を追加
  {
    "env": {
      "node": true
    }
  }
])

これで解決。

、、と思ったら、Chrome devtoolのコンソール上で「processなんてないよ!」みたいなエラーが。。。

スクリーンショット 2026-07-18 11.17.46.png

ほんとの解決方法

Viteで環境構築したら、以下2つのルールを守らなくちゃいけないらしい。

  1. .envファイルに設定する環境変数は、頭にVITE_とつけなきゃいけいない
  2. コードで.envファイルの環境変数を呼び出す場合は、process.env.XXXじゃなくてimport.meta.env.XXXで呼び出す

なので、環境変数を参照する側のコード以下のようにする。

lib/clients/supabase.js
import { createClient } from "@supabase/supabase-js"

export const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
)

おわりに

仕事で扱うソースコードは特に何も考えずにprocess.env.使えてたからこういう下ごしらえが必要だったのは知らなかった。

参考

こちらの記事が最初にヒットしましたが、こちらでは.eslintrc.jsonというファイルをいじってるんですね。

こちらはVite環境変数のルールに気づかせてくれた記事。

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