2

I am trying to get the "version" from the package.json is nextjs application.

I have tried process.env.npm_package_version like in node application but it's returning undefined.

eliezra236
  • 547
  • 1
  • 4
  • 16

2 Answers2

4

You can use process.env.npm_package_version only if you installed the package package_vars before (see: https://docs.npmjs.com/cli/v6/using-npm/scripts#packagejson-vars)

But the simplest way in your case is to import your package.json file (which is a mere .json file) like this:

const { version } = require('./package.json');
console.log(version);
Paul-Marie
  • 874
  • 1
  • 6
  • 24
  • Thank you, that worked, but for typescript it need to be imported like so `import * as pack from '../../package.json';` and then `const version = pack.version;` – eliezra236 Nov 09 '22 at 09:05
  • Sorry, I only read the first tag (which is `javascript`) – Paul-Marie Nov 09 '22 at 09:07
  • Correction, next.js prefer no recasting, so `import pack from '../../package.json';` It will show warning with re-casting or importing just the version – eliezra236 Nov 10 '22 at 07:26
4

in NextJs you can create a next.config.js file and below lines.

const { version } = require('./package.json');

module.exports = {
  publicRuntimeConfig: {
    version,
  },
};

then when you need the version anywhere in app

import getConfig from 'next/config';

const { publicRuntimeConfig } = getConfig();
const version = publicRuntimeConfig?.version

for more info read this article.