Bookmarks
ReferenceBackendVerified

Node.js

Node.js is a server-side JavaScript runtime. This reference covers the event loop, ESM and CommonJS modules, npm, files, HTTP, streams, node:test and security.

checked 5 Nov · next check 12 Nov · 52 min read

Sections
13
Reading
52 min
Current version
26.13.0
Written from
nodejs.org/docs/latest/api

Check status of the reference

Verified 5 Nov · next check 12 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Node.js is and how it works

Node.js is a runtime for JavaScript outside the browser: the V8 engine executes your code, while the node: modules and the libuv library give it access to files and the network. People use Node.js to write HTTP servers and APIs, network services and command-line tools.

A Node.js application runs in a single process and does not create a thread for each request. While I/O is in progress — reading a file, querying a database or calling over the network — the JavaScript thread does not sit idle but runs the callbacks of other requests. When the operation completes, Node.js returns to its result. That is why one server can hold thousands of concurrent connections without any manual thread handling.

Node.js is strongest where there is a lot of I/O and little computation: HTTP APIs, services with many connections, scripts. Heavy computation in JavaScript occupies the main thread, and while it runs, every other client waits. Split such work into chunks or move it to separate threads — see the “Event loop” section for details.

Node.js is built in layers. Your code calls built-in modules such as node:fs, node:http and node:crypto. The V8 engine executes the JavaScript, and the modules pass system operations through C++ bindings to the libuv library. libuv runs the event loop. It asks the OS to watch sockets and files — epoll on Linux, kqueue on macOS, IOCP on Windows — and calls a callback when an event is ready. Whatever the OS cannot do asynchronously — file operations, dns.lookup(), heavy crypto and zlib functions — is handled by the libuv thread pool (the worker pool).

The event loop serves the network and timers, while the thread pool handles files, dns.lookup(), crypto and zlib.

How Node.js differs from the browser

AspectNode.jsBrowser
Who chooses the versionyou: the server’s Node.js version is known in advancethe visitor: the browser and its version are not known in advance
DOM: document, windownoyes
Files and networkmodules such as node:fs and node:httponly through browser APIs; no file system
ModulesES modules (import) and CommonJS (require())ES modules (import)
Global objectsglobalThis, process, Buffer; require and __dirname only in CommonJSglobalThis, window, document
Shared web APIsfetch, URL, AbortController, TextEncoder, structuredClonethe same

Code that uses neither the DOM nor node: modules often works in both environments: fetch(), Headers and AbortController in Node.js are compatible with their browser counterparts. The global object in Node.js is globalThis; global is kept for compatibility. A variable declared at the top level of a file stays inside the module and does not become global.

What you need to know first

  • JavaScript: functions, objects, promises, async/await, the import and export syntax — see the JavaScript reference.
  • The command line: running programs, environment variables — see the Linux and Bash references.
  • For servers, HTTP methods, status codes and headers — see the HTTP and REST reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday commands and calls: running code, npm, files, HTTP and the process. Replace the names in the examples (app.js, undici, data.txt) with your own; for details, see the sections on modules, npm, files, HTTP and security.

Running

TaskCommand
Run a scriptnode app.js
Restart on file changesnode --watch app.js
Load variables from .envnode --env-file=.env app.js
Run TypeScript without a build stepnode app.ts
Check syntax without runningnode --check app.js
Print the result of an expressionnode -p "process.versions.v8"
Interactive console (REPL)node
Run testsnode --test
Run with the debuggernode --inspect app.js

npm

TaskCommand
Create package.jsonnpm init -y
Install the dependencies from package.jsonnpm install
Add a dependencynpm install undici
Add a development dependencynpm install -D eslint
Clean install from the lockfile (CI)npm ci
Install without devDependenciesnpm ci --omit=dev
Run a script from scriptsnpm run build
Run the test and start scriptsnpm test, npm start
Pass arguments to a scriptnpm run lint -- --fix
Run a command from a packagenpx eslint .
See which dependencies are outdatednpm outdated
Known vulnerabilitiesnpm audit

Files

Functions come from node:fs/promises, join from node:path.

TaskHow to write it
Read a text fileawait readFile('data.txt', 'utf8')
Write or replace a fileawait writeFile('out.txt', text)
Append to the endawait appendFile('app.log', line)
Create a directory with its parentsawait mkdir('a/b/c', { recursive: true })
List a directoryawait readdir('.')
File size(await stat('data.txt')).size
Remove a whole directoryawait rm('tmp', { recursive: true, force: true })
Path next to the modulejoin(import.meta.dirname, 'data.txt')

HTTP

TaskHow to write it
Server on port 3000createServer((req, res) => res.end('ok')).listen(3000)
JSON responseres.writeHead(200, { 'Content-Type': 'application/json' })
Request body as a stringawait text(req) from node:stream/consumers
GET requestconst res = await fetch(url)
Request with a 5 s timeoutfetch(url, { signal: AbortSignal.timeout(5000) })
Stop accepting connectionsserver.close()

Process

TaskHow to write it
Environment variableprocess.env.PORT ?? '3000'
Command-line argumentsprocess.argv.slice(2)
Exit with an error codeprocess.exitCode = 1
Exit immediatelyprocess.exit(1)
Handle the stop signalprocess.on('SIGTERM', shutdown)
Node.js, V8 and libuv versionsprocess.versions

Dangerous commands

TaskCommand
See what will go to the registrynpm publish --dry-run
Publish a packagenpm publish
Fix vulnerabilities within version rangesnpm audit fix
Fix, allowing major versionsnpm audit fix --force
Clean reinstall: node_modules is removed automaticallynpm ci
Debugger for this machine onlynode --inspect app.js

Section sources

the section is written from these pages

Installation and first run

For production, use the LTS line. The official download page offers the nvm version manager for Linux and macOS, ready-made installers for macOS and Windows, and a Docker image. Verify the result with node --version and npm --version.

Linux and macOS: nvm

A version manager keeps several Node.js versions side by side and switches between them when different projects need different lines. nvm installs into your home directory ($HOME/.nvm), and nvm install 26 downloads the latest release of the 26 line together with npm.

bashin a terminal
# download and run the nvm installercurl -o- \  https://raw.githubusercontent.com/nvm-sh/nvm/v0.41.0/install.sh \  | bash# load nvm in this shell without restarting it\. "$HOME/.nvm/nvm.sh"nvm install 26

Without a version manager, the same page offers ready-made archives (Standalone Binary) and the Docker image node:26-slim. To open a shell in a container from that image, run docker run -it --rm --entrypoint sh node:26-slim.

macOS and Windows: installer

On the download page, choose your OS, architecture and the LTS line, then download the installer (Installer). It installs node and npm.

Checking the installation

bashin a terminal
node --versionnpm --version
textexample output
v26.x.y11.x.y

Node.js prints the version with a v prefix, npm without it. If the shell cannot find nvm or node, open a new terminal: the nvm installer hooks into new sessions.

REPL

node with no arguments opens the REPL, a console that evaluates JavaScript expressions and prints the result immediately. Built-in modules are available in it without importing: fs, path. The .help command lists the commands, and .exit closes the console.

consoleREPL
> 1 + 12> path.extname('report.pdf')'.pdf'> .exit

Your first project

A Node.js project is a directory with a package.json file. npm init -y creates it without asking questions; the --init-type=module flag writes "type": "module", which makes .js files in the project ES modules (without it, npm writes commonjs).

bashin a terminal
mkdir myapp && cd myappnpm init -y --init-type=module
textproject tree
myapp/├── package.json└── app.js
javascriptapp.js
const started = new Date().toISOString();console.log(`Hello, Node.js! Started at ${started}`);
bashin a terminal
node app.js# restart on every file savenode --watch app.js

With --watch, Node.js tracks the entry file and every file it imports, and restarts the process when they change.

TypeScript without a build step

Node.js runs .ts files with no flags (since 22.18): before executing, it strips type annotations, interfaces and import type (type stripping). Types are not checked, and syntax that needs code generation — enum, namespaces with code — requires a separate build. See the TypeScript reference for details.

bashin a terminal
node app.ts# check types with a separate commandnpx tsc --noEmit

Section sources

the section is written from these pages

Modules: ESM and CommonJS

Node.js has two module systems: ES modules (ESM) with the standard import and export, and the original CommonJS with require() and module.exports. Node.js decides which one applies to a file by its extension and the type field in package.json, and, if there are no explicit signs, by the syntax of the code.

ES modules are the official JavaScript standard and browsers understand them too. CommonJS is the original Node.js module system. The two are interoperable: an ES module can import a CommonJS module, and require() can load an ES module as long as it has no top-level await.

How Node.js chooses a module system

The decision is made for each file, in order. First the extension: .mjs is always an ES module, .cjs is always CommonJS. For .js and extensionless files, the type field in the nearest parent package.json matters. If there is no such field, Node.js looks at the code: import, export, import.meta or top-level await make the file an ES module; otherwise it runs as CommonJS. Syntax detection slows loading down, so set type explicitly — even if all your code is CommonJS.

The type field applies to .js files in the directory with the package.json and in all nested directories, until another package.json is found.

ES modules

jsonpackage.json
{ "type": "module" }
javascriptmath.js
export function add(a, b) {  return a + b;} export default function square(x) {  return x * x;}
javascriptapp.js
import square, { add } from './math.js'; console.log(add(2, 3), square(4));

In import, write a relative path in full, with the extension: ./math.js, not ./math. A whole directory cannot be imported either — you need ./lib/index.js. JSON is imported with a type attribute, and it provides only the default export:

javascriptapp.js
import config from './config.json' with { type: 'json' };

CommonJS

javascriptmath.cjs
function add(a, b) {  return a + b;} module.exports = { add };
javascriptapp.cjs
const { add } = require('./math.cjs');const path = require('node:path'); console.log(add(2, 3), path.basename(__filename));

Node.js wraps each CommonJS file in a function, so module variables are not visible from outside, and require, module, exports, __dirname and __filename exist only inside CommonJS. require() adds the .js, .json and .node extensions by itself and loads a directory as a module. You can assign values to properties of exports, but to set a new object as a whole, use module.exports.

Built-in modules: the node: prefix

Import built-in modules with the node: prefix — node:fs, node:path, node:http. The prefix unambiguously points to a built-in module and bypasses the require cache. Newer modules — node:test, node:sqlite, node:ffi — are available only with the prefix: without it, the name could clash with an npm package.

Paths relative to the module file

ES modules have no __dirname or __filename. Use import.meta.dirname and import.meta.filename instead (stable since Node.js 24 and 22.16), and point to a file next to the module with new URL() based on import.meta.url:

javascriptapp.js
import { readFile } from 'node:fs/promises'; // directory and full path of the current moduleconsole.log(import.meta.dirname, import.meta.filename); // the path is resolved from the module file, not from the current directoryconst file = new URL('./data.json', import.meta.url);const data = JSON.parse(await readFile(file, 'utf8'));

require() for ES modules

Since Node.js 22.12, require() can also load ES modules, and since 25.4 this is a stable feature. There is one condition: neither the module nor its dependencies may use top-level await. require() returns a namespace object, in which the default export is the default property.

javascriptapp.cjs
// util.mjs — an ES module without top-level awaitconst { greet } = require('./util.mjs'); console.log(greet('Node.js'));

require() cannot load a module with top-level await and throws ERR_REQUIRE_ASYNC_MODULE; load such a module with an import() expression, which also works in CommonJS.

Packages: the exports field

The exports field in a package’s package.json defines its entry points and closes off everything else: importing a path that is not in exports fails with ERR_PACKAGE_PATH_NOT_EXPORTED. For new packages, the documentation recommends exports over main; if both are set, exports wins.

jsonthe package’s package.json
{  "name": "money-utils",  "type": "module",  "exports": {    ".": {      "import": "./dist/index.js",      "require": "./dist/index.cjs"    },    "./format": "./dist/format.js",    "./package.json": "./package.json"  }}

Conditional exports pick a file depending on how the package is loaded. The order of keys matters: the first matching condition wins, so put default last.

ConditionWhen it applies
importthe package is loaded with import or import()
requirethe package is loaded with require()
module-syncfor any way of loading; the file is an ES module without top-level await
nodein any Node.js environment
defaultalways; the fallback

Section sources

the section is written from these pages

npm and package.json

npm is the Node.js package manager. A project is described by its package.json file: the name, dependencies with ranges of acceptable versions, and scripts. The exact versions of the whole dependency tree are recorded in package-lock.json, and npm ci uses it to reproduce the installation exactly.

package.json

jsonpackage.json
{  "name": "orders-api",  "version": "1.4.0",  "private": true,  "type": "module",  "engines": { "node": ">=26" },  "scripts": {    "start": "node server.js",    "dev": "node --watch server.js",    "test": "node --test",    "lint": "eslint ."  },  "dependencies": {    "undici": "^8.12.0"  },  "devDependencies": {    "eslint": "^10.14.0"  }}
FieldWhat it sets
name, versionThe package name and version; required only for publishing
privatetrue makes npm refuse to publish the package
typeHow Node.js reads .js files: module or commonjs; npm itself does not use this field
scriptsCommands for npm run
dependenciesPackages the program needs at run time
devDependenciesPackages needed only for development: tests, linters, builds
enginesThe Node.js and npm versions the package works with; unless engine-strict is set, a mismatch only produces a warning
workspacesDirectories of nested packages in one repository (["./packages/*"]): npm links them into a shared node_modules

Versions and ranges

npm package versions follow semantic versioning: MAJOR.MINOR.PATCH. Bug fixes that do not change behaviour increase the patch number (1.0.1), new backwards-compatible features increase the minor version (1.1.0), and breaking changes increase the major version (2.0.0). A range in package.json states which updates of a dependency you are willing to accept:

EntryWhat it allows
1.4.2Only this version
~1.4.2Patches: 1.4.x, at least 1.4.2
^1.4.2Minor versions and patches: 1.x.x, at least 1.4.2
1.4.xAny 1.4 patch
>=1.4.0 <2.0.0Versions within explicit bounds
*Any version

npm install undici adds the package to dependencies with a range rather than an exact version. The -D flag (--save-dev) writes the package to devDependencies, and -E (--save-exact) saves the exact version.

npm install or npm ci

npm install with no arguments installs dependencies into node_modules. If the versions in package-lock.json satisfy the ranges in package.json, npm uses them; if you changed a range, npm picks new versions and updates the lockfile. npm ci is meant for CI and deployment: it installs from scratch, strictly from the lockfile.

Situationnpm installnpm ci
No package-lock.jsonInstalls from package.jsonFails
Lockfile does not match package.jsonUpdates the lockfileFails
node_modules already existsInstalls into itDeletes it and installs again
Writes to package.json and the lockfileYesNever
Add a single packagenpm install nameNot possible

Keep package-lock.json in the repository: it gives every developer and CI the same versions, and npm ci does not work without it. For production, skip the development packages:

bashin CI or a Dockerfile
npm ci --omit=dev

Scripts

Scripts from scripts are run with npm run name; for start, test, stop and restart, npm start or npm test is enough. Before a build script, npm runs prebuild itself, and postbuild after it. A script runs in the package root wherever you invoke npm, and commands of installed packages from node_modules/.bin are written by name, without a path.

jsonpackage.json
{  "scripts": {    "prebuild": "node scripts/clean.js",    "build": "node scripts/build.js",    "postbuild": "node scripts/copy-assets.js"  }}
bashin a terminal
# runs prebuild, build and postbuildnpm run buildnpm test

A script that exits with a non-zero code stops npm. Do not put sudo in scripts, and avoid install and preinstall scripts unless you really need them: prepare exists for preparing a package. Checking dependencies for vulnerabilities (npm audit) is covered in the “Security” section.

Section sources

the section is written from these pages

Event loop

The event loop is the mechanism through which a single JavaScript thread serves all of Node.js I/O. Slow operations go to the OS kernel or the thread pool, and their callbacks run one at a time once the result is ready. While one callback is running, the others wait.

Phases of the loop

Node.js runs your script and then cycles through the phases of the loop. Each phase has its own queue of callbacks: Node.js runs them until the queue is empty or a limit is reached, then moves on to the next phase. In the poll phase the loop waits for new events if there is nothing else to do. When there are no timers and no pending I/O left, the process exits on its own.

The event loop cycles through the pending callbacks, poll, check, close callbacks and timers phases; in the poll phase new connections and data arrive. Microtasks run after every operation, and when there is nothing left to wait for, the process exits.
PhaseWhat runs
pending callbacksI/O callbacks deferred to the next iteration, for example some TCP errors
pollNew I/O events and their callbacks; this is where the loop waits if there is nothing to do
checksetImmediate() callbacks
close callbacks'close' events on an abrupt close, for example after socket.destroy()
timerssetTimeout() and setInterval() callbacks whose time has elapsed

The internal idle, prepare phase is not visible to your code. Since Node.js 20 (libuv 1.45), timers run after the poll phase. The time in setTimeout() is a lower bound: the callback runs no earlier than that, but may run later if the loop is busy.

Microtasks: process.nextTick() and promises

The process.nextTick() queue and the microtask queue (the then, catch and finally callbacks of promises, and queueMicrotask()) are not part of any phase. Node.js drains them after every operation, before the loop moves on: first the nextTick queue, and straight after it the microtasks. A recursive process.nextTick() call can therefore keep the loop from ever reaching I/O.

Order of execution: an example

javascriptorder.js, ES module
import { readFile } from 'node:fs'; readFile(import.meta.filename, () => {  setTimeout(() => console.log('timeout'), 0);  setImmediate(() => console.log('immediate'));  process.nextTick(() => console.log('nextTick'));  Promise.resolve().then(() => console.log('promise'));  console.log('callback');});
textexample output
callbacknextTickpromiseimmediatetimeout

The current callback finishes first, then the microtasks run. Inside an I/O callback, setImmediate() always fires before setTimeout(…, 0): check comes right after poll, and timers come later. Called from the main module, outside I/O, these two fire in an unpredictable order.

What blocks the loop

The loop is blocked when one callback runs for a long time and other clients wait for it. An attacker can do this deliberately by crafting the input, which is a denial of service. Typical causes:

  • Synchronous APIs in a request handler: fs.readFileSync(), zlib.inflateSync(), crypto.pbkdf2Sync(), child_process.execSync(). In a server, use the asynchronous versions.
  • JSON.parse() and JSON.stringify() on large objects: the time grows with the size, so limit the size of the input.
  • Vulnerable regular expressions (ReDoS): nested quantifiers such as (a+)* and backreferences take exponential time on a crafted string. For finding a substring, indexOf() is enough.
  • Algorithms whose time grows faster than linearly with the size of the request: limit the length of the input.
javascriptDo not do this
import { createServer } from 'node:http';import { readFileSync } from 'node:fs'; // while the file is being read, the server answers no onecreateServer((req, res) => {  res.end(readFileSync('report.json'));}).listen(3000);
javascriptserver.js
import { createServer } from 'node:http';import { readFile } from 'node:fs/promises'; createServer(async (req, res) => {  res.end(await readFile('report.json'));}).listen(3000);

Heavy computation

Split a long computation into parts and hand control back to the loop with setImmediate(): during the pauses it can serve other clients. If there is a lot of computation, move it to a worker_threads thread: threads run JavaScript in parallel and exist precisely for computation. They add almost nothing for I/O, where the built-in asynchronous APIs are more efficient.

javascriptfib.js
import { Worker, isMainThread, parentPort, workerData }  from 'node:worker_threads'; function fib(n) {  return n < 2 ? n : fib(n - 1) + fib(n - 2);} if (isMainThread) {  const worker = new Worker(new URL(import.meta.url), {    workerData: 35,  });  worker.on('message', (result) => {    console.log(`fib(35) = ${result}`);  });  worker.on('error', (err) => console.error(err));  console.log('main thread is free');} else {  parentPort.postMessage(fib(workerData));}
textexample output
main thread is freefib(35) = 9227465

Starting a thread is expensive: do not create a thread per task, keep a thread pool instead. For the same reason, do not spawn a child process for every request. A thread cannot see the objects of the main thread: data is passed as a copy through postMessage(), and shared memory is possible only through SharedArrayBuffer.

The libuv thread pool

Asynchronous node:fs operations (except file watching), dns.lookup(), crypto.pbkdf2(), crypto.scrypt(), crypto.randomBytes() and the zlib functions run in the libuv thread pool. It has 4 threads by default: if long tasks occupy all of them, the other operations from this list wait. The pool size is set by the UV_THREADPOOL_SIZE variable at startup; changing it from code is too late, because the pool has already been created.

bashin a terminal
UV_THREADPOOL_SIZE=8 node server.js

Section sources

the section is written from these pages

File system

The node:fs module works with files and directories in three styles: promises (node:fs/promises), callbacks, and synchronous functions with the Sync suffix. In server code, use promises: a synchronous call stops the event loop until the operation finishes.

Which style to choose

StyleWhat it looks likeWhen to use it
Promisesawait readFile(path, 'utf8')The main choice for applications and servers
CallbacksreadFile(path, 'utf8', (err, data) => {})When maximum speed and low memory use matter
SynchronousreadFileSync(path, 'utf8')Short scripts; not in request handlers

The first argument of a callback is always reserved for the error: null or undefined if everything succeeded. Synchronous functions throw immediately, so catch the exception with try…catch. Promise-based operations run in the thread pool, outside the event loop.

Basic operations

javascriptfiles.js
import {  mkdir, writeFile, appendFile,  readFile, readdir, stat, rm,} from 'node:fs/promises';import { join } from 'node:path'; const dir = join(import.meta.dirname, 'data');const file = join(dir, 'notes.txt'); await mkdir(dir, { recursive: true });await writeFile(file, 'first line\n');await appendFile(file, 'second line\n'); console.log(await readFile(file, 'utf8'));console.log(await readdir(dir));const info = await stat(file);console.log(info.size, info.isFile()); await rm(dir, { recursive: true, force: true });
textexample output
first linesecond line [ 'notes.txt' ]23 true
FunctionWhat it doesWorth knowing
readFile(path, 'utf8')Reads the whole fileReturns a Buffer if no encoding is given
writeFile(path, data)Creates a file or replaces its contentsThe default flag is 'w'
appendFile(path, data)Appends to the end, creating the file if it does not existThe default flag is 'a'
mkdir(path, { recursive: true })Creates a directory together with its parentsWithout recursive, an existing directory is an error
readdir(path)Names in a directory, without . and ..withFileTypes, recursive
stat(path)Size, dates and type: isFile(), isDirectory()Throws if the path does not exist
rm(path, { recursive: true })Deletes a file or a directory with its contentsforce: true suppresses the error if the path does not exist

Paths: relative to what

A relative path in node:fs is resolved against the current directory of the process (process.cwd()), not against the file containing the code. Run the script from a different directory and readFile('config.json') will read another file or fail to find it. To build a path relative to the module, use import.meta.dirname, the directory of the current module, together with path.join():

javascriptapp.js
import { readFile } from 'node:fs/promises';import { join } from 'node:path'; const configPath = join(import.meta.dirname, 'config.json');const text = await readFile(configPath, 'utf8');const config = JSON.parse(text);

path.join() joins path segments and normalises the result, path.resolve() gives an absolute path, and path.basename() and path.extname() give the file name and extension. On Windows, node:path works with Windows paths; on other systems it works with POSIX paths.

Large files: use streams

readFile() and readFileSync() load the whole file into memory, which costs a lot of memory and time on large files. Read them as a stream instead: createReadStream() delivers the file in 64 KiB chunks, and only the current chunk is held in memory.

javascriptsize.js
import { createReadStream } from 'node:fs'; let bytes = 0;for await (const chunk of createReadStream('access.log')) {  bytes += chunk.length;}console.log(`${bytes} bytes`);

For how to connect streams without losing errors, see the “Streams” section.

Watching for changes

fs.watch() and watch() from node:fs/promises report changes to a file or directory using OS mechanisms: inotify on Linux, kqueue and FSEvents on macOS. Behaviour differs between platforms, and watching may not work on network drives or in directories mounted in Docker or Vagrant.

File operation errors

An OS error arrives as an object with a code field, and the path that could not be opened is in the path field. Check code, not the message text:

javascriptconfig.js
import { readFile } from 'node:fs/promises'; async function loadConfig(path) {  try {    return JSON.parse(await readFile(path, 'utf8'));  } catch (err) {    // no file: fall back to the default settings    if (err.code === 'ENOENT') return {};    throw err;  }}
CodeWhat happened
ENOENTNo file or directory exists at that path
EACCESFile permissions forbid the operation
EEXISTThe file already exists, but the operation needs a new one
EISDIRA file was expected, but the path is a directory
ENOTDIRPart of the path is not a directory
EMFILEToo many files are open at once

Section sources

the section is written from these pages

HTTP server and client

The node:http module runs an HTTP server without any framework: createServer() calls your handler for every request and passes it the request and response objects. For outgoing requests, Node.js has a global fetch() that is compatible with the browser one.

A server with routes

javascriptserver.js
import { createServer } from 'node:http';import { text } from 'node:stream/consumers'; const json = { 'Content-Type': 'application/json' }; const server = createServer(async (req, res) => {  const { pathname } = new URL(req.url, 'http://localhost');   if (req.method === 'GET' && pathname === '/health') {    res.writeHead(200, json);    res.end(JSON.stringify({ status: 'ok' }));    return;  }   if (req.method === 'POST' && pathname === '/echo') {    try {      const body = JSON.parse(await text(req));      res.writeHead(201, json);      res.end(JSON.stringify(body));    } catch {      res.writeHead(400).end('invalid JSON\n');    }    return;  }   res.writeHead(404).end('not found\n');}); const port = Number(process.env.PORT ?? 3000);server.listen(port, '127.0.0.1', () => {  console.log(`listening on http://127.0.0.1:${port}`);});
bashin another terminal
curl http://127.0.0.1:3000/healthcurl -X POST -H 'Content-Type: application/json' \  -d '{"name":"Ali"}' http://127.0.0.1:3000/echo
textexample output
{"status":"ok"}{"name":"Ali"}

req is an IncomingMessage object: the method is in req.method, and the path with the query string but without the host is in req.url. Headers are in req.headers, and their names are always lower case. res is a ServerResponse: set the status and headers with res.writeHead() or with res.statusCode and res.setHeader() before the first write of the body. Then write the body with res.write() and always finish with res.end(), otherwise the client waits for the response until it times out.

The request body arrives as a stream, in Buffer chunks. The text() function from node:stream/consumers collects it into a string, and JSON.parse() throws on invalid JSON; catch that error and reply with status 400. Routing here is a comparison of the method and path; when routes and shared logic multiply, put a framework on top of node:http.

Server timeouts and limits

SettingDefaultWhat it limits
server.headersTimeout60,000 ms, but no more than requestTimeoutTime allowed to receive the request headers
server.requestTimeout300,000 msTime allowed to receive the whole request
server.timeout0, no limitSocket inactivity
server.maxHeadersCount1000Number of headers in a request
16 KiBSize of the request headersWhen headersTimeout or requestTimeout expires, the server replies with status 408 and closes the connection without passing the request to the handler. The documentation calls for non-zero values if there is no reverse proxy in front of the server: otherwise slow clients can cause a denial of service.

Graceful shutdown

server.close() stops accepting new connections and closes idle ones, and its callback is called once the server has closed completely. Shut the server down on the SIGTERM signal:

A SIGTERM handler cancels the default behaviour, which is to exit immediately, so the process ends by itself once the server has closed and there is nothing left to wait for. Connections that are still sending a request or waiting for a response are cut by server.closeAllConnections() after server.close(). Windows has no SIGTERM signal.

javascriptserver.js
process.on('SIGTERM', () => {  console.log('SIGTERM: closing the server');  server.close(() => console.log('server closed'));});

HTTPS

HTTPS

node:https is the same HTTP over TLS. Pass a key, a certificate and a handler to https.createServer(); everything else works as in node:http. For how to obtain a certificate, see the TLS and PKI reference.

javascripthttps-server.js
import { createServer } from 'node:https';import { readFileSync } from 'node:fs'; const options = {  key: readFileSync('private-key.pem'),  cert: readFileSync('certificate.pem'),}; createServer(options, (req, res) => {  res.end('hello over TLS\n');}).listen(8443);

Client: fetch()

The global fetch() works as it does in the browser and is built on Undici, an HTTP client written for Node.js from scratch. Check res.ok before reading the body. To limit the request time, pass an AbortSignal.timeout() signal: it aborts the request after the given number of milliseconds.

javascriptclient.js
const res = await fetch('https://api.example.com/orders', {  method: 'POST',  headers: { 'Content-Type': 'application/json' },  body: JSON.stringify({ item: 'book', qty: 2 }),  signal: AbortSignal.timeout(5000),});if (!res.ok) {  throw new Error(`HTTP ${res.status}`);}const order = await res.json();

Since Node.js 26.1, an incoming request has req.signal: it is aborted if the client disconnects before getting a response. Pass it to fetch() or a database query so that no work is wasted:

javascriptproxy.js
const RATES_URL = 'https://api.example.com/rates'; createServer(async (req, res) => {  try {    const upstream = await fetch(RATES_URL, { signal: req.signal });    res.end(await upstream.text());  } catch (err) {    // the client is gone: nobody to reply to    if (err.name === 'AbortError') return;    res.writeHead(502).end('upstream error\n');  }}).listen(3000);

Section sources

the section is written from these pages

Streams

A stream is an object that moves data in chunks: a file, an HTTP request, compression. This lets you process a large amount of data without loading it into memory all at once. Connect streams with pipeline() from node:stream/promises: it forwards errors and destroys all the streams if one of them fails.

The four types of stream

TypeWhat it doesExamples
Readablea source you read fromfs.createReadStream(), the http.IncomingMessage request, process.stdin
Writablea destination you write tofs.createWriteStream(), process.stdout, process.stderr
Duplexreads and writes independentlynet.Socket
Transforma Duplex that changes data on the flyzlib.createGzip()

All streams are EventEmitters. A Readable announces new data with the 'data' event and the end with 'end'; any stream reports a failure with 'error'. By default streams carry strings and Buffers; use objectMode for arbitrary JavaScript values. If all the data is already in memory, a stream only adds overhead.

pipeline() instead of .pipe()

.pipe() connects streams but leaves error handling to you: if a stream in the middle fails, the others are not told and are not closed, so memory leaks. On error, pipeline() destroys all the streams, and the version from node:stream/promises returns a promise that rejects with that error.

javascriptgzip.js
import { createReadStream, createWriteStream } from 'node:fs';import { pipeline } from 'node:stream/promises';import { createGzip } from 'node:zlib'; try {  await pipeline(    createReadStream('access.log'),    createGzip(),    createWriteStream('access.log.gz'),  );  console.log('done');} catch (err) {  console.error('pipeline failed:', err.message);  process.exitCode = 1;}

Backpressure

If a source produces data faster than the destination accepts it, the data piles up in memory. Backpressure prevents this: when the destination’s buffer exceeds highWaterMark, write() returns false, the source pauses, and it resumes after the 'drain' event. pipeline() and .pipe() do this for you, so the pipeline’s memory stays flat.

pipeline() destroys all three streams if any link fails.

By default, highWaterMark is 64 KiB for byte streams (16 KiB on Windows) and 16 objects in objectMode.

If you write to a Writable yourself, check the result of write() and wait for 'drain' after false. Otherwise Node.js buffers everything you write until memory runs out, and a socket whose data nobody reads may never be released.

javascriptnumbers.js
import { createWriteStream } from 'node:fs'; const out = createWriteStream('numbers.txt'); for (let i = 1; i <= 1_000_000; i++) {  // false: the buffer is full, wait for 'drain'  if (!out.write(`${i}\n`)) {    await new Promise((resolve) => out.once('drain', resolve));  }}out.end();

Reading with for await

Every Readable is async iterable, so you can read it with a for await…of loop. The loop respects backpressure by itself — the next chunk arrives once you have processed the previous one — and errors are caught with an ordinary try…catch. You can put an async generator straight into pipeline() as a transform:

javascriptupper.js
import { createReadStream, createWriteStream } from 'node:fs';import { pipeline } from 'node:stream/promises'; await pipeline(  createReadStream('input.txt', { encoding: 'utf8' }),  async function* (source) {    for await (const chunk of source) {      yield chunk.toUpperCase();    }  },  createWriteStream('output.txt'),);

With encoding: 'utf8', the stream yields strings and correctly reassembles multi-byte characters that straddle chunk boundaries. If you take chunks as Buffers and call toString() on each one, Cyrillic text can get corrupted at a chunk boundary.

A custom Transform

javascripttransform.js
import { Transform } from 'node:stream';import { pipeline } from 'node:stream/promises'; const upper = new Transform({  transform(chunk, encoding, callback) {    callback(null, chunk.toString().toUpperCase());  },}); await pipeline(process.stdin, upper, process.stdout);

The transform() method receives a chunk and passes the result to callback(null, data); pass an error as the first argument, callback(err). Call callback only when the chunk has been fully processed.

Web Streams

Besides Node.js streams, there are Web Streams from the WHATWG standard: ReadableStream, WritableStream and TransformStream, as in the browser. Their API is different and they are not directly compatible with Node.js streams; the toWeb() and fromWeb() methods, such as Readable.fromWeb(), convert one into the other. pipeline() also accepts Web Streams.

Section sources

the section is written from these pages

Testing

The node:test module is the built-in Node.js test runner: tests, suites, hooks, mocks and code coverage without third-party libraries. Write assertions with node:assert/strict and run them with node --test.

Your first test

javascriptsrc/price.js
export function total(items, discount = 0) {  if (discount < 0 || discount > 1) {    throw new RangeError('discount must be in [0, 1]');  }  const sum = items.reduce(    (acc, item) => acc + item.price * item.qty,    0,  );  return Math.round(sum * (1 - discount));} export async function fetchRate(currency) {  const url = `https://api.example.com/rates/${currency}`;  const res = await fetch(url);  return (await res.json()).rate;}
javascripttest/price.test.js
import { describe, it } from 'node:test';import assert from 'node:assert/strict';import { total } from '../src/price.js'; describe('total', () => {  it('sums price × qty', () => {    const items = [      { price: 100, qty: 2 },      { price: 50, qty: 1 },    ];    assert.equal(total(items), 250);  });   it('applies a discount', () => {    assert.equal(total([{ price: 200, qty: 1 }], 0.1), 180);  });   it('rejects a discount above 1', () => {    assert.throws(() => total([], 2), RangeError);  });});
bashin the terminal
node --test
textexample output
▶ total  ✔ sums price × qty (0.39ms)  ✔ applies a discount (0.08ms)  ✔ rejects a discount above 1 (0.22ms)✔ total (1.21ms)ℹ tests 3ℹ suites 1ℹ pass 3ℹ fail 0...

describe() and it() are aliases of suite() and test(). A test fails if its function throws or returns a rejected promise. If any test fails, the process exit code is 1, so CI sees the failure.

node:assert/strict enables strict mode: assert.equal() behaves like assert.strictEqual(), assert.deepEqual() like assert.deepStrictEqual(), and on failure the message shows the difference between the values.

AssertionWhat it asserts
assert.equal(actual, expected)the values are strictly equal
assert.deepEqual(actual, expected)objects and arrays have equal contents
assert.ok(value)the value is truthy
assert.match(text, /regexp/)the string matches the regular expression
assert.throws(fn, RangeError)the function throws an error of the given type
await assert.rejects(promise)the promise rejects

Running from the command line

With no arguments, node --test looks for tests by these patterns: *.test.js, *-test.js, *_test.js, test-*.js, test.js and every file in test/ directories. The extensions .js, .mjs and .cjs match, and so do .ts, .mts and .cts. Each file runs in a separate process. Quote your own patterns so the shell does not expand them.

bashin the terminal
node --testnode --test "src/**/*.spec.js"# only tests with discount in their namenode --test --test-name-pattern="discount"# re-run on changesnode --test --watch

The test runner’s --watch mode is experimental: it re-runs only the tests affected by a change. Add the script "test": "node --test" to package.json so that npm test runs your tests.

Async tests and timeouts

An async test is an async function: the runner waits for its promise. The timeout option fails a test that runs longer than the given number of milliseconds; there is no limit by default. The --test-timeout flag sets a global limit for all tests. Await subtests inside test() with await t.test(…): otherwise the parent test finishes first and cancels them.

javascripttest/timeout.test.js
import { test } from 'node:test';import assert from 'node:assert/strict'; test('responds within 2 s', { timeout: 2000 }, async () => {  const started = Date.now();  await new Promise((resolve) => setTimeout(resolve, 100));  assert.ok(Date.now() - started >= 100);});

Mocks: functions, methods, timers

The mock object from node:test and the same API on the test context, t.mock, create spies and replacements. Prefer t.mock: after the test, the runner restores everything that was replaced.

javascripttest/mock.test.js
import { test } from 'node:test';import assert from 'node:assert/strict';import { fetchRate } from '../src/price.js'; test('fetchRate reads the rate field', async (t) => {  const fakeFetch = async () => ({    json: async () => ({ rate: 12650 }),  });  const fake = t.mock.method(globalThis, 'fetch', fakeFetch);   assert.equal(await fetchRate('USD'), 12650);  assert.equal(fake.mock.callCount(), 1);  assert.match(fake.mock.calls[0].arguments[0], /USD$/);}); test('timers without waiting', (t) => {  const fn = t.mock.fn();  t.mock.timers.enable({ apis: ['setTimeout'] });  setTimeout(fn, 60_000);  t.mock.timers.tick(60_000);  assert.equal(fn.mock.callCount(), 1);});
CallWhat it does
t.mock.fn(impl)a spy function: counts calls and records arguments
t.mock.method(obj, 'name', impl)replaces an object’s method
fn.mock.callCount()the number of calls
fn.mock.calls[0].argumentsthe arguments of the first call
t.mock.timers.enable({ apis: ['setTimeout'] })replaces timers
t.mock.timers.tick(ms)moves time forward without waiting

Code coverage

The --experimental-test-coverage flag collects coverage and prints a per-file table after the tests; in Node.js 26 the feature is still experimental. Files from node_modules and the tests themselves are left out of the report. The lcov reporter writes a report for external tools.

bashin the terminal
node --test --experimental-test-coverage# write an lcov report to lcov.infonode --test --experimental-test-coverage \  --test-reporter=lcov --test-reporter-destination=lcov.info
textexample output
ℹ start of coverage reportℹ ----------------------------------------------------------ℹ file      | line % | branch % | funcs % | uncovered linesℹ ----------------------------------------------------------ℹ src       |        |          |         |ℹ  price.js | 100.00 |   100.00 |  100.00 |ℹ ----------------------------------------------------------ℹ all files | 100.00 |   100.00 |  100.00 |ℹ ----------------------------------------------------------ℹ end of coverage report

Tests that depend on execution order can be found with the --test-randomize flag (since 26.1, early development): it shuffles files and tests and prints the seed. --test-random-seed=number repeats the same order.

Section sources

the section is written from these pages

Security

The main threats to a Node.js application are malicious or compromised dependencies, denial of service from slow or heavy requests, and running commands built from user input. Node.js trusts all the code it runs, including packages from node_modules, so the application has to defend itself.

Dependencies

Any package in the dependency tree can read files and send data over the network, and its postinstall script runs at install time. Attacks come through typos in package names, compromised maintainer accounts and tampered lockfiles.

  • Install dependencies in CI with npm ci: if the lockfile and package.json disagree, it fails instead of silently updating the lockfile.
  • Commit package-lock.json: it pins the versions of the whole tree, including transitive dependencies, which an exact version in package.json does not pin.
  • Disable install scripts where you do not need them: npm ci --ignore-scripts or npm config set ignore-scripts true.
  • Set a cooldown for new versions: min-release-age in .npmrc (npm 11.10 and later) stops you installing a version younger than the given number of days. Most malicious versions are found and removed within hours.
  • Check package names in package.json: a typo installs someone else’s package.
  • Check for known vulnerabilities with npm audit in CI.
ini.npmrc
# do not install versions younger than one daymin-release-age=1
bashin CI
npm ci --ignore-scripts# fail only on high and critical vulnerabilitiesnpm audit --audit-level=high# update vulnerable packages within their rangesnpm audit fix

npm audit needs a lockfile and exits with a non-zero code if it finds vulnerabilities at or above --audit-level. npm audit fix --force also installs major versions outside the ranges in package.json, so run your tests afterwards. For an urgent fix without the cooldown, use npm install undici --min-release-age=0.

Before npm publish, check the list of files with npm publish --dry-run: the whole directory goes to the registry except what .npmignore and .gitignore exclude. An allowlist is set by the files field in package.json.

Permission model

The --permission flag turns on the permission model: the process is denied the file system, network, child processes, worker_threads, native addons, WASI modules, FFI and the inspector until you allow them with --allow-* flags. It is a seat belt against mistakes in trusted code, not a sandbox: malicious code can bypass it.

bashin the terminal
node --permission \  --allow-fs-read=./config \  --allow-fs-write=./logs \  --allow-net \  server.js
FlagWhat it allows
--allow-fs-read=pathreading files; repeat the flag for several paths
--allow-fs-write=pathwriting files
--allow-netnetwork connections
--allow-child-processspawning child processes
--allow-workerworker_threads
--allow-addonsnative addons
--allow-wasiWASI modules
--allow-ffiFFI modules; only in builds with FFI support

The entry-point file is read without a separate permission. A forbidden operation throws an ERR_ACCESS_DENIED error; to check a permission from code, use process.permission.has('fs.write', './logs'). Before enabling the model, run the application with --permission-audit: access is not denied, and each violation is published to node:diagnostics_channel, so you can see which permissions you need.

Secrets come from the environment

Do not keep passwords and keys in code or in the repository: pass them through environment variables. For development, keep them in a .env file and load it with the --env-file flag; in code, read the value from process.env.DB_PASSWORD. A variable set in the environment takes precedence over the value in the file. Add .env to .gitignore.

ini.env
DB_PASSWORD=change-meAPI_TOKEN=change-me
bashin the terminal
node --env-file=.env server.js

Denial of service

Slow requests (the Slowloris attack) arrive in pieces and keep connections open until the server hits its limit. To defend against them:

  • Put a reverse proxy in front of Node.js: it accepts connections, caches and balances the load.
  • Configure the server timeouts headersTimeout, requestTimeout, timeout and keepAliveTimeout so that slow and idle connections are closed.
  • Limit the number of sockets: server.maxRequestsPerSocket and, on the client, agent.maxSockets and agent.maxTotalSockets.
  • Handle socket errors: a server without an 'error' handler crashes on a malformed request.
  • Do not enable insecureHTTPParser: lenient parsing opens the door to HTTP request smuggling between the proxy and the application.

OS commands: execFile() instead of exec()

exec() hands the whole string to a shell, so special characters from user input (;, |, $()) become new commands. execFile() runs the program directly, without a shell, and takes arguments as an array.

javascriptdo not do this
import { exec } from 'node:child_process'; // dir came from a request: “; rm -rf ~” will runexec(`ls -l ${dir}`, (err, stdout) => {  console.log(stdout);});
javascriptlist.js
import { execFile } from 'node:child_process';import { promisify } from 'node:util'; const run = promisify(execFile); // arguments are an array, no shell involvedconst { stdout } = await run('ls', ['-l', '--', dir]);

Do not enable the shell option in execFile() and spawn() when the arguments contain user input: it brings back the same vulnerability.

Other rules

  • Prototype pollution is tampering with Object.prototype properties through a __proto__ key in incoming JSON, for example during a deep merge of objects. Validate external data with a JSON schema, create dictionaries with Object.create(null), and check keys with Object.hasOwn().
  • Compare secrets with crypto.timingSafeEqual(): the time of an ordinary string comparison leaks the content. Hash passwords with crypto.scrypt().
  • Do not use experimental features in production: they may change, and their security is not settled.

Section sources

the section is written from these pages

Common errors and diagnostics

Start diagnosing with the Node.js version (node -v), the error’s code field and the first stack line that points to your file. The message text can change between versions, but code is a stable signature: search by it.

Order of checks

  1. Check the version: node -v. Code written for a newer release line may not work on an older one.
  2. Find the error’s code: ENOENT, ERR_MODULE_NOT_FOUND. System errors also have syscall, path, address and port.
  3. Read the stack from the top down to the first line from your own code.
  4. If the cause is unclear, run the program under a debugger: node --inspect-brk app.js.

MODULE_NOT_FOUND and ERR_MODULE_NOT_FOUND

Cause: the loader could not find a file or package. require() throws MODULE_NOT_FOUND; import and running a file as an ES module throw ERR_MODULE_NOT_FOUND.

  • The package is not installed: run npm install, or npm ci in CI.
  • The extension is missing from an import: write ./utils.js, not ./utils; for a directory, ./lib/index.js.
  • A relative path in import and require() is resolved from the importing file.

ERR_REQUIRE_ASYNC_MODULE

Cause: require() is loading an ES module that has a top-level await, either in itself or in its dependencies. The old ERR_REQUIRE_ESM error is obsolete: require() now loads synchronous ES modules.

javascriptapp.cjs
// instead of require('./config.mjs')import('./config.mjs').then(({ config }) => {  start(config);});

To find exactly where the await is, run with the --experimental-print-required-tla flag.

An ES module runs as CommonJS

Symptom: a SyntaxError on a line with import or export. Cause: the file is explicitly marked as CommonJS — by the .cjs extension or by "type": "commonjs" in the nearest package.json — and Node.js does not recognise ES module syntax in it.

  • Rename the file to .mjs or set "type": "module" in package.json.
  • Or rewrite the file with require() and module.exports.

EADDRINUSE

Cause: the address and port are already taken by another server on this machine — for example, a second copy of your application. Stop the old process or start the server on a different port.

javascriptserver.js
server.on('error', (err) => {  if (err.code === 'EADDRINUSE') {    console.error(`port ${err.port} is busy`);    process.exitCode = 1;  }});
bashin the terminal
PORT=3001 node server.js

ECONNREFUSED

Cause: nothing is accepting connections at the target address — the service is not running, or the address or port is wrong. Check that the service is running and compare the address and port in the error with your connection settings.

ENOENT and EACCES

Cause: ENOENT means there is no file or directory at the path; EACCES means permissions forbid the operation. The path that failed to open is in the error’s path field. Relative paths in node:fs are resolved from the process’s current directory, not from the file containing the code.

javascriptapp.js
try {  await readFile('config.json', 'utf8');} catch (err) {  // what failed, where, and in which call  console.error(err.code, err.syscall, err.path);}

To fix paths, build them from the module: join(import.meta.dirname, 'config.json').

ERR_ACCESS_DENIED

Cause: the process was started with --permission, and the operation lacked a permission. The error’s permission (FileSystemRead, ChildProcess and others) and resource fields say exactly which. Add the flag you need: --allow-fs-read=./data, --allow-net, --allow-child-process.

Unhandled promise rejection

Symptom: the process exits with an error from a promise that nobody caught. Cause: the promise has no catch, and there is no try…catch around the await. By default (--unhandled-rejections=throw), such a rejection becomes an uncaught exception and terminates the process.

javascripthandler.js
try {  await saveOrder(order);} catch (err) {  console.error('order not saved:', err);  res.writeHead(500).end();}

The --unhandled-rejections=strict mode turns a rejection into an exception even if an unhandledRejection event handler is installed; warn mode only prints a warning.

JavaScript heap out of memory

Cause: the V8 heap has reached its limit — data is growing without bound (a memory leak), or the task genuinely needs more memory. The full text is: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory.

bashin the terminal
# heap snapshots as it nears the limit, at most threenode --heapsnapshot-near-heap-limit=3 app.js# raise the heap limit to 4 GiB if memory is shortnode --max-old-space-size=4096 app.js

Compare the .heapsnapshot files with each other: objects whose count grows from snapshot to snapshot point to a leak. Snapshots take time and memory, so the process may exit even sooner.

Debugging with the inspector

node --inspect app.js starts the inspector on 127.0.0.1:9229; --inspect-brk also pauses the program before the first line of your code. Connect from Chrome via chrome://inspect, from VS Code, or with the command-line debugger node inspect app.js. Reach a remote server through an SSH tunnel rather than opening port 9229 to the network.

bashin the terminal
node --inspect-brk app.js# from your machine: port 9221 leads to the server’s 9229ssh -L 9221:localhost:9229 ali@app.example.com

Other system errors

CodeCauseWhat to do
ECONNRESETthe peer dropped the connection: a timeout or a restartretry the request; compare timeouts on both sides
ETIMEDOUTthe peer did not respond in timecheck that the address is reachable; close connections with socket.end()
ENOTFOUNDDNS could not find the host namecheck the host name and DNS
EPIPEwriting to a connection that the other side has closedcheck that the connection is still open before writing
EMFILEtoo many open filesclose the ones you do not need; on macOS, raise the limit: ulimit -n 2048
EPERMthe operation needs elevated privilegesrun the process with the required privileges
ERR_PACKAGE_PATH_NOT_EXPORTEDthe path inside the package is not declared in its exports fieldimport through a declared entry point
ERR_HTTP_HEADERS_SENTresponse headers are changed after they have been sentset the status and headers before writing the body, and respond only once

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Node.js 26.x “Lithium”, an Active LTS release line. The latest release is 26.13.0, from 28 October 2026. From Node.js 27 onwards, one major version is released each year and receives 30 months of long-term support (LTS): 36 months pass from the first Current release to End-of-Life. Up to and including 26, only even-numbered versions became LTS.

LineStatusLatest releaseSupported until
26.x “Lithium”Active LTS from 28 October 2026, Maintenance from 20 October 202726.13.0 — 28 October 202630 April 2029
24.x “Krypton”Maintenance LTS from 20 October 202624.22.2 — 27 October 202630 April 2028
22.x “Jod”Maintenance LTS from 21 October 202522.23.4 — 20 October 202630 April 2027
20.x “Iron”support has ended20.20.2 — 24 March 202630 April 2026

In production, use only Active LTS and Maintenance LTS lines. Active LTS receives proven new features and fixes; Maintenance receives critical fixes and security updates. The 27.x line is currently in the Alpha phase: its releases are meant for library authors and CI, not for production.

What changed in 26

  • What Node.js is and how it works: the V8 engine is updated to 14.6, and the language gains Map.prototype.getOrInsert(), getOrInsertComputed() and Iterator.concat(). The Temporal API, a modern replacement for Date, is enabled by default.
  • HTTP server and client: fetch() runs on Undici 8; an incoming request has a req.signal that aborts when the client disconnects (since 26.1).
  • Testing: --test-randomize and --test-random-seed shuffle the test order (since 26.1). t.log() writes messages to the report immediately (since 26.6), and --test-coverage-include-all adds files that the tests did not load to the coverage report (since 26.7).
  • Security: process.permission.drop() revokes a granted permission at runtime (since 26.3).
  • Event loop: a global Worker class following the Web Workers standard on top of node:worker_threads is experimental, behind the --experimental-web-worker flag (since 26.9).

Deprecated and removed

  • ServerResponse.prototype.writeHeader() was removed in 26.0; use writeHead().
  • The _stream_wrap, _stream_readable, _stream_writable, _stream_duplex, _stream_transform and _stream_passthrough modules were removed in 26.0; import node:stream instead.
  • The --experimental-transform-types flag was removed in 26.0: Node.js only strips types, and TypeScript features that generate code (enum) require a build step.
  • module.register() has emitted a warning (DEP0205) since 26.0 and will be removed; switch to module.registerHooks().
  • Passing a CryptoKey to node:crypto functions (DEP0203) and a non-extractable CryptoKey to KeyObject.from() (DEP0204) have emitted a warning since 26.0 and will become an error in future.
  • Short GCM authentication tags without an explicit authTagLength have not been accepted since 26.0 (DEP0182).
  • The type option of Duplex.toWeb() has emitted a warning since 26.0 (DEP0201); use readableType.

Security updates

IdentifierWhat is affectedFixed in
CVE-2026-106069, CVE-2026-106072, CVE-2026-105483node:tls: non-canonical IP addresses and their normalisation during certificate verification (High)26.12.1
CVE-2026-105482node:dns: null bytes in resolve input (High)26.12.1
CVE-2026-111497Brotli decompression in node:zlib (High)26.12.1
CVE-2026-105481, CVE-2026-106074, CVE-2026-106070, CVE-2026-106071, CVE-2026-106073node:http agent, crypto random number cache in snapshots, ZIP headers in zlib, permission model: path patterns and realpathSync (Medium and Low)26.12.1
CVE-2026-56848HTTP/2: stream reset (High)26.5.1
CVE-2026-58043Permission model: a bug in the allowed-paths tree (High)26.5.1
CVE-2026-56850, CVE-2026-58040, CVE-2026-58041, CVE-2026-58042, CVE-2026-58045, CVE-2026-56847, CVE-2026-58039, CVE-2026-58044https agent, node:sqlite, dns.resolveAny(), zlib, permission model, HTTP header count limit (Medium and Low)26.5.1
CVE-2026-48618, CVE-2026-48933TLS: hostname normalisation during certificate verification; WebCrypto: cipher output length (High)26.3.1
CVE-2026-48615, CVE-2026-48619, CVE-2026-48928, CVE-2026-48930, CVE-2026-48934, CVE-2026-48617, CVE-2026-48931, CVE-2026-48935, CVE-2026-48936Proxy credentials in error messages, originSet in HTTP/2, SNI selection, null bytes in hostnames, TLS sessions, http.Agent response queue, permission model (Medium and Low)26.3.1

How to upgrade

  1. Install the new line with a version manager: nvm install 26.
  2. Update the engines field in package.json, the Node.js version in CI and the image in your Dockerfile (node:26-slim).
  3. Read “Deprecated and removed” and the release notes for the versions between yours and the new line.
  4. Run your tests on the new line.
  5. On Linux, when moving from 24 or 22, check for the libatomic library. Official builds have linked against it since Node.js 25, and some distributions package it separately.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Node.js” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61