Next.jsで$yarn run dev(next) した際に、 .env.local と .env.staging を使い分けられるようにします。
下準備
それぞれの.envに値を追加しておきます
.env.local
API_URL=http://localhost:4000.env.staging
API_URL=https://hogehoge.comnext.config.jsの編集
nextのプロジェクト内で環境変数を使えるよう「next.config.js」を編集しておきます。
next.config.js
module.exports = {
env: {
API_URL: process.env.API_URL,
},
}パッケージ導入
それぞれのenvを npm-scripts実行時に切り替えられるよう env-cmd というパッケージを追加します
$ yarn add -D env-cmdpackage.jsonを編集します
package.json
"scripts": {
"dev:local": "env-cmd -f .env.local next",
"dev:stg": "env-cmd -f .env.staging next"
},後はNext.jsで使用するコード内で process.env.API_URL とすれば、
$yarn run dev:local $yarn run dev:stg で環境に応じて使い分けることが出来ます。
const baseUrl = process.env.API_URL
const url = `${baseUrl}/v1/users`
// yarn run dev:local => http://localhost:4000/v1/users
// yarn run dev:stg => https://hogehoge.com/v1/users
const res = await axios.get(url)
・・・