1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

本番ビルドの実行で.envを正しく読み込む

Last updated at Posted at 2025-12-01

小ネタです。
pnpmを使ってReact Router 7 RSC Framework modeで作成したアプリをビルド・実行する方法について記します。

以下の「公式」テンプレートを使用して作成したアプリを前提とします。

// 普通のRR7アプリの場合
npx create-react-router@latest my-react-router-app

// RSCを試している場合
npx create-react-router@latest --template remix-run/react-router-templates/unstable_rsc-framework-mode

開発環境でのアプリ実行

pnpm run dev

process.env.XXXXXXで参照している環境変数は問題なく取り込まれます。

本番環境向けのビルドと実行

// ビルド
pnpm run build

// 実行
pnpm start

これだけだと.envの内容が読み込まれません(サーバーサイドにファイルがないので当然)。

実際のところ、環境変数の値を渡してアプリを実行するには、環境変数と値のペアを最初に指定して実行コマンドを起動する必要があります。

DATABASE_URL=postgresql://user:password@databasepath COOKIE_SECRET=6Hyur44.... pnpm start

もちろん、毎回こんなことを入力するわけにはいきません(セキュリティのためにも不可)ので、env-cmdパッケージを導入して解決します。

pnpm add -D env-cmd

プロジェクトのpackage.jsonを変更します。

"scripts": {
    "build": "react-router build",
    "dev": "react-router dev",
    "start": "react-router-serve build/server/index.js",
    // この行を追加
    "start-local": "env-cmd react-router-serve build/server/index.js",

startのスクリプトを変えると、デプロイ先(Dockerなど)で支障が出る可能性があるため、新たにstart-localスクリプトを追加し、env-cmdで取得する.envの内容をreact-router-serveの頭に付けるように指定しています。

これで、シークレットに触れることなく本番ビルドを起動できます。

pnpm start-local

参考資料
  1. RR7オフィシャル: https://reactrouter.com/start/framework/installation
  2. RR7オフィシャル: https://reactrouter.com/how-to/react-server-components
  3. env-cmd: https://www.npmjs.com/package/env-cmd
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?