Prevent npm install for not supported Node.js versions
- Published at
- Updated at
- Reading time
- 2min
Yesterday I reviewed a pull request to Contentful's Gatsby starter and learned a nifty detail about npm configurations.
The pull request's goal was to guarantee that users run the project with a specific Node.js version. You can do so by defining the engines
property in your package
to specify a version range.
{
"engines": {
"node": ">=15.0.0"
}
}
But even though many projects define a minimum Node.js version, this package
configuration is not enforcing the environment. When I run npm install
in a project with a not supported Node.js version, the following warning (EBADENGINE
) is displayed.
$ npm install
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'engine-test@1.0.0',
npm WARN EBADENGINE required: { node: '>=15.0.0' },
npm WARN EBADENGINE current: { node: 'v14.15.0', npm: '7.5.3' }
npm WARN EBADENGINE }
That's it and all npm does in this scenario. It displays a warning but is not failing and preventing the user from going on.
It turns out you can add a local npm configuration file (
) to your module/project root and explicitly turn on strict Node.js engine handling.
engine-strict=true
If a project includes an
that defines a strict engine, people cannot run npm install
if their Node.js is not fulfilling the version requirement. ๐ The warning EBADENGINE
becomes an error, and the installation process fails with a status code 1
.
$ npm install
npm ERR! code EBADENGINE
npm ERR! engine Unsupported engine
npm ERR! engine Not compatible with your version of node/npm: engine-test@1.0.0
npm ERR! notsup Not compatible with your version of node/npm: engine-test@1.0.0
npm ERR! notsup Required: {"node":">=15.0.0"}
npm ERR! notsup Actual: {"npm":"7.5.3","node":"v14.15.0"}
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/stefanjudis/.npm/_logs/2021-02-21T15_34_32_743Z-debug.log
Yarn doesn't need an additional configuration file and treats the engines
property strictly by default. This seems like the correct way to handle Node.js versions.
$ yarn install
yarn install v1.22.5
info No lockfile found.
[1/5] ๐ Validating package.json...
error engine-test@1.0.0: The engine "node" is incompatible with this module. Expected version ">=15.0.0". Got "14.15.0"
error Found incompatible module.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
And that's all it takes to prevent folks from using your project with an unsupported Node.js version! ๐ If you liked this post, make sure to check out my weekly newsletter in which I share more web development learning or have a look at more Node.js posts.
Join 5.5k readers and learn something new every week with Web Weekly.