Setting Node.js Version Requirements in package.json
Ensuring that everyone runs your project on the correct Node.js version is essential for avoiding unexpected bugs, failing builds, and inconsistencies between development and production. In this guide, you’ll learn how to define Node.js version requirements in package.json, enforce them across environments, and validate versions in local development and CI/CD pipelines.
1. Define Node.js Version With the engines Field
The simplest way to specify supported Node.js versions is by adding the engines field to your package.json.
Example:
{
"engines": {
"node": ">=18.0.0 <21.0.0"
}
}This configuration means:
- Minimum version: 18.0.0
- Maximum version: anything below 21
You can use semver ranges to express different compatibility conditions.
Common semver examples
| Syntax | Meaning |
|---|---|
"18.x" | Any Node.js version 18 |
">=16" | 16 or newer |
"^20.0.0" | 20.x.x but not 21 |
">=14 <18" | Node.js 14–17 |
2. Enforce Version Strictly With npm (engine-strict)
By default, npm does not block installation if the version does not match.
To enforce strict compatibility, enable:
npm config set engine-strict trueThis makes npm refuse to install dependencies when the Node.js version does not meet the requirement.
Useful for teams and large codebases.
To commit this rule to the project, add it to .npmrc:
engine-strict=true3. Enforcing Node Version in CI/CD
Your CI pipeline should use the same Node.js version as your local development and production.
GitHub Actions Example
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npm testThis ensures that CI runs on Node.js 20, matching your requirements in package.json.
GitLab CI Example
image: node:20
stages:
- test
test:
script:
- npm ci
- npm test4. Use nvm for Local Development
To test and switch Node.js versions locally, use nvm (Node Version Manager).
Install Node.js 20:
nvm install 20Switch to Node.js 20:
nvm use 20Set a default global version:
nvm alias default 20.nvmrc file
Create a .nvmrc file for automatic version switching:
20Developers can now run:
nvm use…and nvm loads the correct version automatically.
5. Pin Node.js Version for Production (Docker)
If you use Docker, always pin a specific version to guarantee a stable runtime.
Example Dockerfile:
FROM node:20-alpine
WORKDIR /app
COPY package*.json .
RUN npm ci
COPY . .
CMD ["npm", "start"]This ensures your production environment is 100% predictable.
Conclusion
Specifying Node.js version requirements helps you:
- Avoid runtime errors caused by incompatible APIs
- Ensure consistent behavior across local machines, CI/CD, and production
- Establish predictable environments for teams and deployments
By combining the engines field, npm’s engine-strict, CI configuration, and tools like nvm, your project stays fully aligned with the correct Node.js version across all environments.