LoginSignup
0
0

More than 1 year has passed since last update.

next.jsで、コード上で環境変数を設定する。

Posted at

環境変数なんだけど秘匿するほどではなくソース管理する方が都合の良い場合がある。
公開されているAPIのエンドポイントとか。

configs/env.js ファイルに環境変数をまとめ、importして使う。
next.config.js の設定が必要。

// configs/env.js
const development = {
  API_ENDPOINT: 'http://test.api.com',
}
const staging = {
  API_ENDPOINT: 'http://test.api.com',
}
const production = {
  API_ENDPOINT: 'http://production.api.com',
}

if (process.env.ENV === 'development') {
  module.exports = development
} else if (process.env.ENV === 'staging') {
  module.exports = staging
} else if (process.env.ENV === 'production') {
  module.exports = production
}
// next.config.js
const webpack = require('webpack')
module.exports = {
  ...
  webpack: (config) => {
    config.plugins.push(
      new webpack.DefinePlugin({
        'process.env.ENV': JSON.stringify(process.env.NODE_ENV)
      })
    )
    return config
  }
}

使い方

// 使うファイル
import env from '.../configs/env'

console.log(`${env.API_ENDPOINT}/hoge`)
// => http://test.api.com/hoge
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