How to show your app version in a Next.js (next js 14 app router)

iconstyank

Kostiantyn

Posted on April 22, 2024

How to show your app version in a Next.js (next js 14 app router)

There are only two ways to deal with JSON in ES modules today:

  1. Read and parse JSON files yourself:
import { readFile } from 'fs/promises';

const json = JSON.parse(
  await readFile(
    new URL('./some-file.json', import.meta.url)
  )
);
Enter fullscreen mode Exit fullscreen mode
  1. Leverage the CommonJS require function to load JSON files:
import { createRequire } from "module";

const require = createRequire(import.meta.url);
const data = require("./data.json");
Enter fullscreen mode Exit fullscreen mode

With Next.js, it’s rather easy to use next.config.js and publicRuntimeConfig.

My footer.tsx:

import getConfig from 'next/config';

export default function Footer() {
  const { publicRuntimeConfig } = getConfig();
  return (
    <footer>
      ...
      <small>
        App Version: {publicRuntimeConfig?.version}
      </small>
    </footer>
  );
}
Enter fullscreen mode Exit fullscreen mode

And my next.config.js:

import { createRequire } from "module";

const require = createRequire(import.meta.url);
const json = require("./package.json");

const nextConfig = {
    ...
    publicRuntimeConfig: {
        version: json.version,
    },
};

export default nextConfig;
Enter fullscreen mode Exit fullscreen mode

Here you go!

💖 💪 🙅 🚩
iconstyank
Kostiantyn

Posted on April 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related