How to enforce node,npm versions in node project | Package.json engines example

This tutorial explains setting NODE and NPM versions in node projects

Multiple ways to define and enforce developers to use specific node and npm versions in different ways.

  • using package.json
  • .npmrc file

package.json engine to enforce node and npm versions in node projects

The engines attribute in package.json tells the application to support only the specific node and npm version.

It tells the application to run on which version of node, npm, or yarn tools.

"engines": {
    "node" : "node version",
    "npm" : "npm version",
    "yarn" : "yarn version"
    "
  }

The values of versions might contain exact matches or between ranges

The below combinations of node versions can be used

  • ”node” : ">=18.0.0 <16.0.0" - It tells to use node version between 16.0.0 and 18.0.0 inclusive only.
  • ”node” : "~>18.0.0" - tilde(~) Use 18.0.0 or patch version such as 18.0.1 to 18.0.9 only.
  • ”node” : "^18.0.0 " - caret(^)Use 18.0.0 or latest minor or patch version such as 18.0.1 to 18.9.9 only.

Examples of engines configuration in package.json

{
  "engines": {
    "node": ">=18.0.0 <16.0.0",
    "npm": ">=9.0.0 <8.5.0"
  }
}

Next, create .npmrc to node project

add engine-strict=true to this file

engine-strict=true

if you are running a node project with the node 15 version, engines contain 18 versions.

It throws an error npm WARN EBADENGINE Unsupported engine while running npm commands such as npm install.

PS B:\work> npm install
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: '[email protected]',
npm WARN EBADENGINE required: { node: '>=18.0.0 <16.0.0' },
npm WARN EBADENGINE current: { node: 'v15.12.0', npm: '6.1.2' }
npm WARN EBADENGINE }

Conclusion

Setting node versions at the project allows developers to restrict unsupported versions. This is useful in production deployments to the cloud such as Heroku, AWS and gcs using docker containers to avoid unsupported errors and warnings