Node.js 22 LTS (Long Term Support) has become the go-to JavaScript runtime for modern web development, offering enhanced performance, security improvements, and cutting-edge features. This comprehensive guide covers multiple installation methods for Node.js 22, from using NVM (Node Version Manager) to Docker containerization, ensuring you can set up your development environment efficiently and securely.
Understanding Node.js 22 – The Complete Overview
Node.js 22, released in April 2024 and transitioned to LTS status in October 2024, represents a significant milestone in JavaScript runtime evolution. With the codename “Jod,” this version brings substantial performance improvements, enhanced security features, and better developer experience. The LTS designation means Node.js 22 will receive active support until October 2025 and maintenance support until April 2027, making it the ideal choice for production applications.
Key highlights of Node.js 22 include improved V8 engine performance, enhanced WebSocket support, experimental –run flag for faster script execution, and better compatibility with modern JavaScript features. The runtime now includes built-in WebSocket globals without requiring the –experimental-websocket flag, streamlining real-time application development.
Prerequisites and Requirements
System Requirements
- Operating Systems: Windows 10+, macOS 10.15+, Linux (Ubuntu 18.04+, CentOS 7+, Alpine 3.9+)
- Architecture: x64, ARM64, ARMv7 (32-bit ARM on select platforms)
- Memory: Minimum 512MB RAM, recommended 2GB+ for development
- Disk Space: 200MB for Node.js installation, additional space for npm packages
- Network: Internet connection for downloading packages and dependencies
Knowledge Prerequisites
- Basic command line interface (CLI) navigation
- Understanding of package managers and dependency management
- Familiarity with JavaScript development concepts
- Basic terminal/shell commands for your operating system
Step-by-Step Installation Guide
Method 1: Using NVM (Node Version Manager) – Recommended
NVM is the most flexible method for installing and managing multiple Node.js versions. This approach allows you to switch between different Node.js versions effortlessly, making it perfect for developers working on multiple projects with varying requirements.
Installing NVM on Linux/macOS
# Download and install NVM
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
# Reload your shell profile (or restart terminal)
source ~/.bashrc
# or for zsh users
source ~/.zshrc
# Verify NVM installation
nvm --version
Installing Node.js 22 with NVM
# Install the latest Node.js 22 LTS version
nvm install 22
# Use Node.js 22 as the current version
nvm use 22
# Set Node.js 22 as the default version
nvm alias default 22
# Verify installation
node -v # Should output v22.11.0 or later
npm -v # Should output 10.9.2 or compatible version
Managing Multiple Node.js Versions
# List all installed versions
nvm list
# List available versions for installation
nvm list-remote
# Switch to a specific version
nvm use 20.10.0
# Install and immediately use a version
nvm install 18.19.0 --use
Method 2: Docker Installation – Containerized Approach
Docker provides a containerized environment for Node.js, ensuring consistency across different development and production environments. This method is particularly useful for CI/CD pipelines and microservices architectures.
Basic Docker Setup
# Pull the official Node.js 22 Alpine image (lightweight)
docker pull node:22-alpine
# Create and run a Node.js container
docker run -it --rm --name nodejs-dev node:22-alpine sh
# Inside the container, verify installation
node -v # Should output v22.11.0 or later
npm -v # Should output 10.9.2 or compatible version
Creating a Development Dockerfile
# Use official Node.js 22 LTS Alpine image
FROM node:22-alpine
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy application code
COPY . .
# Expose port
EXPOSE 3000
# Start application
CMD ["node", "server.js"]
Docker Compose for Development
version: '3.8'
services:
nodejs-app:
build: .
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules
environment:
- NODE_ENV=development
command: npm run dev
Method 3: Official Installer – Direct Installation
The official Node.js installer provides a straightforward installation process for users who prefer GUI-based setup or need system-wide installation without version management complexity.
Windows Installation
- Visit the official Node.js website
- Download the Windows Installer (.msi) for Node.js 22 LTS
- Run the installer with administrator privileges
- Follow the installation wizard, ensuring “Add to PATH” is selected
- Restart your command prompt or PowerShell
macOS Installation
- Download the macOS Installer (.pkg) from the official website
- Double-click the installer and follow the setup wizard
- Enter your administrator password when prompted
- Open Terminal and verify installation
Linux Package Managers
# Ubuntu/Debian using NodeSource repository
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt-get install -y nodejs
# CentOS/RHEL/Fedora
curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -
sudo yum install -y nodejs
# Arch Linux
sudo pacman -S nodejs npm
# Verify installation
node --version
npm --version
Basic Configuration and Setup
Initial Configuration
After installation, configure npm and Node.js for optimal development experience. This includes setting up npm registry preferences, configuring global package locations, and establishing security settings.
# Check npm configuration
npm config list
# Set npm registry (optional, for private registries)
npm config set registry https://registry.npmjs.org/
# Configure npm to use a specific directory for global packages
npm config set prefix /usr/local
# Set npm to save exact versions by default
npm config set save-exact true
# Configure npm audit level
npm config set audit-level moderate
Setting Up a New Project
# Create new project directory
mkdir my-nodejs-project
cd my-nodejs-project
# Initialize npm package
npm init -y
# Install development dependencies
npm install --save-dev nodemon jest eslint
# Install production dependencies
npm install express dotenv helmet cors
# Create basic project structure
mkdir src tests config
touch src/index.js tests/app.test.js config/database.js
Verification and Testing
Verify your Node.js 22 installation by creating a simple test application and checking all components work correctly.
// Create test file: test-installation.js
console.log('Node.js Version:', process.version);
console.log('NPM Version:', process.env.npm_version);
console.log('Platform:', process.platform);
console.log('Architecture:', process.arch);
// Test ES6+ features
const testAsync = async () => {
const data = await Promise.resolve('Async/Await working!');
console.log(data);
};
testAsync();
// Test modern JavaScript features
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log('Array map result:', doubled);
# Run the test file
node test-installation.js
# Expected output should show Node.js v22.x.x and confirm feature support
Advanced Features and Techniques
Feature 1: Built-in WebSocket Support
Node.js 22 introduces native WebSocket support without requiring experimental flags, streamlining real-time application development.
// WebSocket server example using built-in support
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
// Echo message back to client
ws.send(`Echo: ${data}`);
});
ws.send('Connected to WebSocket server');
});
console.log('WebSocket server running on port 8080');
Feature 2: Enhanced –run Flag Performance
The experimental –run flag provides faster script execution compared to npm run, offering significant performance improvements for build processes.
{
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js",
"test": "jest",
"build": "webpack --mode production",
"lint": "eslint src/**/*.js"
}
}
# Traditional npm run approach
npm run test
# Faster --run flag approach (Node.js 22)
node --run test
# Performance comparison shows ~2x speed improvement
# Benchmark results: node --run test is 2.04x faster than npm run test
Best Practices and Optimization
Performance Optimization
- Use .nvmrc files: Create project-specific Node.js version requirements
- Optimize package.json: Use exact versions and minimal dependencies
- Enable V8 optimizations: Leverage Node.js 22’s improved V8 engine features
- Memory management: Monitor heap usage and implement proper garbage collection strategies
- Clustering: Utilize Node.js cluster module for CPU-intensive operations
# Create .nvmrc file for project consistency
echo "22" > .nvmrc
# Use .nvmrc in project
nvm use # Automatically uses version specified in .nvmrc
# Monitor Node.js performance
node --inspect app.js # Enable debugging/profiling
node --max-old-space-size=4096 app.js # Increase heap size
Security Considerations
- Regular updates: Keep Node.js and npm updated to latest patch versions
- Dependency auditing: Use npm audit to identify vulnerabilities
- Environment variables: Secure sensitive configuration data
- Package verification: Verify package integrity before installation
- Minimal permissions: Run applications with least required privileges
# Security audit commands
npm audit # Check for vulnerabilities
npm audit fix # Automatically fix issues where possible
npm audit fix --force # Force fixes (use with caution)
# Update to latest secure versions
npm update # Update all packages
npm outdated # Check for outdated packages
Troubleshooting Common Issues
Issue 1: Permission Errors on Global Package Installation
Problem: EACCES permission errors when installing global packages with npm
Solution: Configure npm to use a different directory for global packages or use a Node.js version manager
# Method 1: Change npm default directory
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
# Method 2: Use npx instead of global installation
npx create-react-app my-app # Instead of npm install -g create-react-app
Prevention: Use NVM or configure npm global directory during initial setup
Issue 2: Version Conflicts Between Projects
Problem: Different projects require different Node.js versions
Solution: Use NVM with .nvmrc files for project-specific version management
# Create .nvmrc in each project
echo "22" > .nvmrc # For Node.js 22 projects
echo "20" > .nvmrc # For Node.js 20 projects
# Automatic version switching with NVM
nvm use # Reads .nvmrc and switches version
Prevention: Always use .nvmrc files and document Node.js version requirements
Issue 3: npm Install Failures Due to Network Issues
Problem: Package installation fails due to network timeouts or proxy issues
Solution: Configure npm network settings and use alternative registries
# Increase npm timeout
npm config set fetch-timeout 600000
npm config set fetch-retry-mintimeout 10000
npm config set fetch-retry-maxtimeout 60000
# Configure proxy (if needed)
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
# Use alternative registry
npm config set registry https://registry.npmmirror.com/
Prevention: Configure corporate proxy settings and registry mirrors during initial setup
Issue 4: Docker Container Build Failures
Problem: Docker build fails with Node.js installation or permission errors
Solution: Optimize Dockerfile and use multi-stage builds
# Optimized Dockerfile for Node.js 22
FROM node:22-alpine AS builder
# Install build dependencies
RUN apk add --no-cache python3 make g++
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
FROM node:22-alpine AS runtime
WORKDIR /app
# Copy only production files
COPY --from=builder /app/node_modules ./node_modules
COPY . .
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nextjs -u 1001
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
Prevention: Use multi-stage builds and non-root users for enhanced security
Real-World Use Cases and Examples
Case Study 1: Microservices Architecture with Node.js 22
A fintech company migrated their monolithic application to microservices using Node.js 22, leveraging improved performance and built-in WebSocket support for real-time trading updates.
// API Gateway service using Node.js 22 features
const express = require('express');
const { WebSocketServer } = require('ws');
const app = express();
// Enhanced error handling with Node.js 22
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
});
// WebSocket for real-time price updates
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
// Send real-time market data
setInterval(() => {
ws.send(JSON.stringify({
symbol: 'BTC/USD',
price: Math.random() * 50000 + 30000,
timestamp: new Date().toISOString()
}));
}, 1000);
});
app.listen(3000, () => {
console.log('API Gateway running on port 3000');
});
Case Study 2: CI/CD Pipeline Optimization
A development team reduced their build times by 40% using Node.js 22’s –run flag and Docker multi-stage builds in their continuous integration pipeline.
# GitHub Actions workflow using Node.js 22
name: CI/CD Pipeline
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [22.x]
steps:
- uses: actions/checkout@v3
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests (using --run flag for performance)
run: node --run test
- name: Build application
run: node --run build
- name: Security audit
run: npm audit --audit-level moderate
Frequently Asked Questions (FAQ)
Q: What’s the difference between Node.js 22 LTS and the current version?
A: Node.js 22 LTS provides long-term support with guaranteed security updates until April 2027, while current versions (like 23.x) include the latest features but have shorter support cycles. LTS versions are recommended for production applications requiring stability and extended support.
Q: Can I run Node.js 22 alongside other Node.js versions?
A: Yes, using NVM (Node Version Manager) allows you to install and switch between multiple Node.js versions seamlessly. This is particularly useful for maintaining legacy projects while developing new applications with the latest features.
Q: Is Node.js 22 compatible with existing npm packages?
A: Node.js 22 maintains excellent backward compatibility with existing npm packages. However, some packages may require updates to leverage new features. Always check package compatibility and run npm audit after upgrading.
Q: What are the performance improvements in Node.js 22?
A: Node.js 22 includes an updated V8 engine, improved garbage collection, enhanced startup performance, and the experimental –run flag that’s approximately 2x faster than npm run for script execution.
Q: How do I migrate from Node.js 18/20 to Node.js 22?
A: Start by installing Node.js 22 using NVM, test your application thoroughly, update deprecated APIs, run security audits, and gradually migrate environments starting with development, then staging, and finally production.
Q: Does Node.js 22 require any code changes for WebSocket support?
A: Node.js 22 includes native WebSocket support without requiring the –experimental-websocket flag. Existing WebSocket code should work without modifications, but you can now remove experimental flags from your startup scripts.
Q: What’s the recommended deployment strategy for Node.js 22 applications?
A: Use Docker containers with multi-stage builds, implement proper health checks, configure logging and monitoring, use process managers like PM2 for production, and ensure your infrastructure supports Node.js 22’s system requirements.
Q: How do I handle security updates for Node.js 22?
A: Subscribe to Node.js security announcements, regularly run npm audit, keep Node.js updated to the latest patch version, monitor CVE databases, and implement automated security scanning in your CI/CD pipeline.
Conclusion and Next Steps
Key Takeaways
- Node.js 22 LTS offers enhanced performance, security, and developer experience with long-term support until 2027
- Multiple installation methods (NVM, Docker, official installer) provide flexibility for different development environments
- Built-in WebSocket support and the –run flag are standout features for modern application development
- Proper configuration and security practices are essential for production deployments
- Version management with NVM enables seamless project switching and dependency management
What’s Next?
After successfully installing Node.js 22, explore building modern applications with Express.js, implement real-time features using native WebSocket support, set up automated testing with Jest, and consider containerizing your applications with Docker for consistent deployment across environments.