5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Next.jsでdotenvを使って秘匿情報を扱う

Last updated at Posted at 2020-01-27

以下の公式ドキュメントではnext.config.jsで環境変数を指定する方法しかなかったので、
使い慣れてるdotenvで秘匿情報を扱いたくなった。

Environment Variables

dotenvではなくdotenv-webpackを使う

dotenvだと環境変数を使うたびに、
require("dotenv").config()を実行する必要がある

そのためdotenv-webpackというライブラリを使うことで、
webpackのコンパイル時にenvファイルの内容をインポートしてくれるようにする。

dotenv-webpackのインストール

yarn add dotenv-webpack --dev

next.config.jsの変更


const path = require('path')
const Dotenv = require('dotenv-webpack')

module.exports = {
  target: "serverless",
  webpack: config => {
    config.plugins = config.plugins || []
    config.plugins = [
      ...config.plugins,
      // Read the .env file
      new Dotenv({
        path: path.join(__dirname, '.env'),
        systemvars: true
      })
    ]
    return config
  }
};

上記のように記述することで.envファイルの中身を使うことができるようになる。
使う側では以下のようにprocess.env.xxxでアクセスする。


process.env.API_KEY
5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?