概要
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,
},
};
};