Universal runtime configuration in Next.js project using node-config
npm install --save config next-config
or
yarn add config next-config
Create a next.config.js
in your project
// next.config.js
const withConfig = require("next-config");
module.exports = withConfig();
Create a custom document pages/_document.js
import Document, { Head, Main, NextScript } from "next/document";
import htmlescape from "htmlesacpe";
import config from "config";
const __NEXT_CONFIG__ = { ...config };
// exclude server config
delete __NEXT_CONFIG__.server;
export default class extends Document {
render() {
return (
<html>
<Head />
<body>
<Main />
<script
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `
__NEXT_CONFIG__ = ${htmlescape(__NEXT_CONFIG__)}
`
}}
/>
<NextScript />
</body>
</html>
);
}
}
Create a config file config/default.json
{
"universalConfigA": "UNIVERSAL_CONFIG_A",
"universalConfigB": "UNIVERSAL_CONFIG_B",
"server": {
"secretA": "SECRET_A",
"secretB": "SECRET_B"
}
}
Create a page file pages/index.js
import config from "config";
const IndexPage = () => (
<div>
Hello World!<br />
${config.get("universalConfigA")}
<br />
${config.get("universalConfigB")}
<br />
</div>
);
IndexPage.getInitialProps = () => {
console.log(config.get("server.secretA"));
console.log(config.get("server.secretB"));
return {};
};
export default IndexPage;
Optionally you can add your custom Next.js configuration as parameter
// next.config.js
const withConfig = require("next-config");
module.exports = withConfig({
webpack(config, options) {
return config;
}
});