LoginSignup
7
5

More than 3 years have passed since last update.

Nextjsでビルド時ではなく、アプリ起動時に環境変数を読み込ませる方法

Posted at

概要

Nextjsでビルド時ではなく、アプリ起動時に環境変数を設定する方法を調べたのでメモとして残している。

next.config.jsの設定

以下のように設定する。

// .envファイルから読み込むように設定している。
require("dotenv").config();

module.exports = {
  // ビルド時に利用できる環境変数
  env: {
    STEP: process.env.MY_STEP,
  },
  // 実行時かつ、サーバサイドで利用できる
  serverRuntimeConfig: {
    MY_SECRET: process.env.MY_SECRET,
  },
  // 実行寺かつ、サーバサイド、クライアントサイドのどちらでも利用できる
  publicRuntimeConfig: {
    API_ENDPOINT: "/my/api/version/1",
  },
};

next.config.jsで設定した値を読み込む方法

例: pages/index.jsで読み込む場合

import getConfig from "next/config";

// next.config.jsで設定した値を取得する
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();

// クライアントサイド: API_ENDPOINTは参照できるが、MY_SECRETは参照不可になっている。
export default function Index(props) {
  return (
    <div>
      API_ENDPOINT: {publicRuntimeConfig.API_ENDPOINT}
      MY_SECRET: {serverRuntimeConfig.MY_SECRET}
      <pre>{JSON.stringify(props, null, 4)}</pre>
    </div>
  );
}

// サーバサイド: MY_SECRETとAPI_ENDPOINTはどちらも参照可能
export const getServerSideProps = () => {
  return {
    props: {
      MY_SECRET: serverRuntimeConfig.MY_SECRET,
      API_ENDPOINT: publicRuntimeConfig.API_ENDPOINT,
    },
  };
};
7
5
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
7
5