How to Lock Your Project’s Node.js Version

I’m chicken you have the right Node.js!

It’s a good idea to ensure your project uses the same Node.js version in all environments. This way you can be sure that your code will work as expected, from development to production.

npm has a built-in feature to check if the running Node.js version is as expected, and fail if not. To configure this fully requires two settings.

First, declare your supported Node.js version in the engines setting in your package.json:

{
  "name": "example",
  "private": true,
  "engines": {
    "node": "16.x"
  }
}

16.x represents “any version starting with 16”. Normally this is sufficient, as in most environments you probably install the latest version in a series, to pull in all bug fixes.

Second, add a .npmrc file next to your package.json with:

engine-strict=true

The engine-strict setting tells npm to stop with an error on unsupported versions. This looks like:

$ npm install
npm ERR! code EBADENGINE
npm ERR! engine Unsupported engine
npm ERR! engine Not compatible with your version of node/npm: example@1.0.0
npm ERR! notsup Not compatible with your version of node/npm: example@1.0.0
npm ERR! notsup Required: {"node":"16.x"}
npm ERR! notsup Actual:   {"npm":"7.7.6","node":"v15.14.0"}

npm ERR! A complete log of this run can be found in:
npm ERR!     /.../.npm/_logs/2022-03-25T11_45_49_682Z-debug.log

Without engine-strict, npm will log a warning, but proceed:

$ npm install
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'example@1.0.0',
npm WARN EBADENGINE   required: { node: '16.x' },
npm WARN EBADENGINE   current: { node: 'v15.14.0', npm: '7.7.6' }
npm WARN EBADENGINE }

up to date in 1s

70 packages are looking for funding
  run `npm fund` for details

Such a warning is easily ignored, especially when npm is invoked automatically by CI tools, etc. So, it’s best to use engine-strict.

Fin

That’s it! May your environments be always aligned.

—Ådam


Make your development more pleasant with Boost Your Django DX.


Subscribe via RSS, Twitter, or email:

One summary email a week, no spam, I pinky promise.

Tags: