11

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.

2
  • nextjs.org/docs/pages/building-your-application/configuring/… Commented Dec 29, 2023 at 9:15
  • @juliomalves: I don't think this question should have been closed as a duplicate. There are specifics for nextjs, which are not generally applicable to nodejs. For example, anything involving next.config.js. Commented Jan 16, 2024 at 7:29

2 Answers 2

16

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.

Update 2023/11/23 : Next js says this feature is deprecated and you better use environment variables for that usage. But you can still do the same thing with publicRuntimeConfig. For better explanation see this part of their docs.

Here is a "modern" version, which works in next 14, at least:

const { version } = require('./package.json');
    
module.exports = {
  env: {
    version
  }
};

You can then access version in the app code by process.env.version

Sign up to request clarification or add additional context in comments.

3 Comments

nextjs.org say this feature is deprecated! [nextjs.org/docs/pages/api-reference/next-config-js/…
@MohmmadEbrahimiAval thanks for the heads up. Answer has been updated
9

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);

4 Comments

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;
Sorry, I only read the first tag (which is javascript)
Correction, next.js prefer no recasting, so import pack from '../../package.json'; It will show warning with re-casting or importing just the version
Is it a security hazard to import package.json? Does Next.js extract the version attribute in the build? In this regard, the question isn't a duplicate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.