There are only two ways to deal with JSON in ES modules today:
Read and parse JSON files yourself:
const json = JSON.parse(
await readFile(
new URL(‘./some-file.json’, import.meta.url)
)
);
Leverage the CommonJS require function to load JSON files:
const require = createRequire(import.meta.url);
const data = require(“./data.json”);
With Next.js, it’s rather easy to use next.config.js and publicRuntimeConfig.
My footer.tsx:
export default function Footer() {
const { publicRuntimeConfig } = getConfig();
return (
<footer>
…
<small>
App Version: {publicRuntimeConfig?.version}
</small>
</footer>
);
}
And my next.config.js:
const require = createRequire(import.meta.url);
const json = require(“./package.json”);
const nextConfig = {
…
publicRuntimeConfig: {
version: json.version,
},
};
export default nextConfig;
Here you go!