Learn Node.js 24 LTS with examples that were actually run: installation and built-in tools, the event loop, async error handling, streams, an Express 5 API server, testing, Docker deployment, operations, and diagnostics.
Intermediate
Updated Oct 10, 2026
~22 min read
22 sections
38 code examples
Web IDE lab included
🟢
Node.js Web IDE
Run code in the browser with nothing to install and learn through step-by-step examples.
Learn Node.js 24 LTS with examples that were actually run: installation and built-in tools, the event loop, async error handling, streams, an Express 5 API server, testing, Docker deployment, operations, and diagnostics. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.
Key perspective
Frontend / app development
Do not stop at drawing the screen: look at state, data requests, routing, accessibility, and the unit of deployment together.
Express 5 API serverEvent loop and asyncBuilt-in test runnerDocker deployment and operationsPerformance diagnostics
Architecture diagrams
To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Node.js.
Learning flow
Rendering diagram…
Architecture view
Rendering diagram…
What is Node.js?
When you first open Node.js, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.
Node.js is a runtime that runs JavaScript outside the browser on Chrome's V8 engine. Its core is non-blocking I/O and the event loop: it does not hold a thread while waiting on file and network I/O, so a single thread serves many connections at once.
This design has clear strengths and limits. It fits servers that spend most of their time waiting on a database or external APIs, and it does not fit servers built around long CPU-bound computation. Use the table below to decide first.
Situation
Fit
Why
REST · GraphQL API servers
Good
Most of each request is I/O: waiting on the database and external APIs.
Many connections are kept open with few resources.
BFF, API gateway
Good
Combines several APIs in the same language as the frontend.
CLI tools, build scripts
Good
The npm ecosystem and fast startup are advantages.
Image · video conversion, heavy computation
Caution
It blocks the event loop. Move it to Worker Threads or a separate service.
Model training · numerical computing
Poor
Python's scientific computing ecosystem is far richer.
Choosing a version and installing
Here you look at Choosing a version and installing alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Node.js ships a new major version every six months, and the even-numbered ones move to LTS (long-term support) around October each year. An LTS release gets security patches for about 30 months, so servers use LTS only. Odd-numbered versions lose support after six months and are not used in production.
This guide is based on Node.js 24 LTS. Different projects end up on different versions, so use a version manager rather than installing from an installer.
macOS · Linux (nvm)BASH
# Follow https://github.com/nvm-sh/nvm to install nvmnvm install 24 # install 24 LTSnvm use 24node --version # v24.x.xnpm --version
Windows · macOS · Linux (fnm)BASH
# fnm works with the same commands on Windows toofnm install 24fnm use 24node --version
Pin the version in the projectBASH
# Write the version to use at the repository rootecho "24" > .nvmrc# After that, no version number is needednvm use # or fnm use
Release status
Meaning
Use on servers
Current
The version receiving the newest features. Even-numbered versions become LTS in October.
No
Active LTS
A long-term support version that receives both new features and bug fixes
Yes (recommended)
Maintenance LTS
Security and critical bug fixes only
Yes (plan the upgrade)
End-of-Life
Security patches have ended
No
npm & package.json
Here you look at npm & package.json alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
package.json is the manifest that lists the project name, dependencies, and run scripts. The package-lock.json created next to it records the exact versions that were installed. npm install installs within the version ranges in package.json and may update the lockfile, while npm ci installs exactly the versions written in the lockfile.
npm install express zod # add dependenciesnpm install -D typescript # add a development dependencynpm ci # install exactly what the lockfile says (CI · Docker)npm outdated # see which packages can be updatednpm audit # check for known vulnerabilitiesnpm run dev # run the dev script
Notation
Allowed range
Example
^5.2.0
Latest version with the same major (minor · patch updates)
5.2.0 or later, below 6.0.0
~5.2.0
Latest version with the same minor (patch updates only)
5.2.0 or later, below 5.3.0
5.2.0
Exactly that version
5.2.0
ES Modules vs CommonJS
Here you look at ES Modules vs CommonJS alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Node.js has two module systems: the older CommonJS (require, module.exports) and ES Modules (import, export), the JavaScript standard. Start new projects with ES Modules. Writing "type": "module" in package.json makes every .js file an ES module.
In ES Modules a relative import cannot omit the file extension, and import.meta.dirname replaces __dirname. Built-in Node.js modules take the node: prefix to tell them apart from npm packages.
ES ModulesJAVASCRIPT
import { readFile } from 'node:fs/promises'; // built-in modules use the node: prefiximport express from 'express'; // npm packageimport { createApp } from './app.js'; // your own files need the extensionexport function helper() {} // named exportexport default createApp; // default export// await works at the top levelconst text = await readFile(new URL('./data.json', import.meta.url), 'utf8');console.log(import.meta.dirname); // directory of this fileconsole.log(import.meta.filename); // absolute path of this file
CommonJS (what you see in existing projects)JAVASCRIPT
Here you look at Built-in tools — watch · env · test · TypeScript alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Development conveniences used to need several packages, but most of them are now part of Node.js. Fewer dependencies mean faster installs and less to audit for security. In a new project, start with the built-in features and add a package when they fall short.
Development serverBASH
# Restarts when a file changes and reads the values in .env as environment variablesnode --watch --env-file=.env src/server.js# To continue without an error when there is no .env filenode --env-file-if-exists=.env src/server.js
node greet.ts# Hello, Mina# Type checking is a separate stepnpx tsc --noEmit
What you want
Package used before
Built in
Restart when files change
nodemon
node --watch src/server.js
Read a .env file
dotenv
node --env-file=.env src/server.js
Run tests
jest, mocha
node --test
HTTP requests
axios, node-fetch
global fetch
Run TypeScript
ts-node, tsx
node app.ts
Parse arguments
yargs, commander
util.parseArgs
Generate UUIDs
uuid
crypto.randomUUID()
Event loop & async
Here you look at Event loop & async alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
In Node.js, JavaScript code runs on one thread. I/O such as reading files or network requests is handed to the operating system and libuv, and when it finishes the event loop runs the callbacks that handle the results, one at a time. The thread is free while waiting, so it can serve other requests.
The other side of this is that when one callback takes a long time, every other request stops. Most Node.js performance problems come from here.
Rendering diagram…
order.js — execution orderJAVASCRIPT
console.log('1. synchronous code');setTimeout(() => console.log('4. setTimeout (timer callback)'), 0);Promise.resolve().then(() => console.log('3. Promise.then (microtask)'));console.log('2. synchronous code');// Output: 1 → 2 → 3 → 4// After all synchronous code finishes, microtasks (Promises) run before timers.
block.js — measuring a blocked event loopJAVASCRIPT
import { monitorEventLoopDelay } from 'node:perf_hooks';const histogram = monitorEventLoopDelay({ resolution: 10 });histogram.enable();// Synchronous work that holds the CPU: no other callback can run during this timefunction blockFor(ms) { const end = Date.now() + ms; while (Date.now() < end) {}}setTimeout(() => blockFor(300), 100);setTimeout(() => { histogram.disable(); console.log('max event loop delay (ms):', Math.round(histogram.max / 1e6));}, 1000);// Output: max event loop delay (ms): 300
Code that blocks the event loop
What to use instead
Sync functions such as readFileSync while handling a request
Regular expressions that slow down sharply with input length
Limit input length, use simpler patterns
Async error handling and timeouts
Here you look at Async error handling and timeouts alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
An unhandled Promise rejection makes Node.js terminate the process. That is exactly what happens when an async function called without await throws. Always await async functions, and when you deliberately do not wait, attach .catch().
Always put a timeout on external calls. Waiting forever on a server that does not respond piles up connections and memory until the whole server stops.
reject.js — when await is missingJAVASCRIPT
async function job() { throw new Error('unhandled error');}job(); // no await and no .catch() → the process terminatessetTimeout(() => console.log('this never runs'), 100);
fetch.js — timeouts and partial failureJAVASCRIPT
async function getJson(url) { // Abort with a TimeoutError when there is no response within 3 seconds const res = await fetch(url, { signal: AbortSignal.timeout(3000) }); if (!res.ok) throw new Error(`request failed: ${res.status} ${url}`); return res.json();}// Use allSettled to get the other results even when one failsconst results = await Promise.allSettled([ getJson('https://registry.npmjs.org/express/latest'), getJson('https://registry.npmjs.org/this-package-does-not-exist-xyz-123/latest'),]);for (const result of results) { if (result.status === 'fulfilled') console.log('ok:', result.value.name); else console.log('failed:', result.reason.message);}// ok: express// failed: request failed: 404 https://registry.npmjs.org/...
Function
Behavior
When to use
Promise.all
Fails immediately when any one fails
When it only makes sense if all succeed
Promise.allSettled
Waits for all and returns each result
When some failures are acceptable
Promise.race
Returns the first result to settle (success · failure)
When implementing a timeout yourself
Promise.any
Returns the first success
When one of several mirrors succeeding is enough
File system and streams
Here you look at File system and streams alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Work with files through the async functions in node:fs/promises. Reading a small file in one go is fine, but readFile on a large file uses as much memory as the file is big. Large data has to flow through a stream a little at a time to keep memory use flat.
To connect streams, use pipeline from stream/promises instead of .pipe(). It closes every stream when an error occurs midway and automatically slows the sender when the receiver is slow (backpressure).
gzip.js — compressing a large file with streamsJAVASCRIPT
import { createReadStream, createWriteStream } from 'node:fs';import { pipeline } from 'node:stream/promises';import { createGzip } from 'node:zlib';// Memory use stays flat regardless of the file sizeawait pipeline( createReadStream('access.log'), createGzip(), createWriteStream('access.log.gz'),);console.log('compressed');
lines.js — reading a large file line by lineJAVASCRIPT
import { createReadStream } from 'node:fs';import { createInterface } from 'node:readline';let errors = 0;const lines = createInterface({ input: createReadStream('access.log'), crlfDelay: Infinity });for await (const line of lines) { if (line.includes(' 500 ')) errors++;}console.log('500 responses:', errors);
HTTP server and fetch
Here you look at HTTP server and fetch alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
You can build a server with node:http alone, without a framework. Doing it once is the way to understand what a framework does for you: you find that routing, body parsing, and error handling are all yours to write.
In the other direction, HTTP requests use the global fetch. It is the same API as in the browser and needs no extra package.
http.js — a server with built-in modules onlyJAVASCRIPT
client.js — sending a request with fetchJAVASCRIPT
const res = await fetch('http://localhost:3000/todos', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'Read the guide' }), signal: AbortSignal.timeout(3000),});if (!res.ok) throw new Error(`request failed: ${res.status}`);console.log(await res.json());
Building an API server with Express 5
Here you look at Building an API server with Express 5 alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Express passes each request through middleware in turn. Middleware runs in the order it was registered with app.use(), so order is behavior. Body parsing goes before the routes, and 404 handling and error handling go last.
In Express 5, an error thrown in an async handler is passed to the error-handling middleware automatically. In Express 4 you had to wrap the handler in try/catch and call next(err) yourself.
The example below separates the function that builds the app (createApp) from the code that starts the server. That way a test can build the app without opening a port.
InstallBASH
npm install express zod
src/app.jsJAVASCRIPT
import express from 'express';import { z } from 'zod';// Defines the shape of the request body and is used for validationconst todoInput = z.object({ title: z.string().trim().min(1).max(200), done: z.boolean().default(false),});class HttpError extends Error { constructor(status, message, details) { super(message); this.status = status; this.details = details; }}export function createApp({ todos = new Map() } = {}) { const app = express(); let nextId = 1; app.disable('x-powered-by'); app.use(express.json({ limit: '100kb' })); // limit the body size app.get('/health', (req, res) => { res.json({ status: 'ok' }); }); app.get('/todos', (req, res) => { res.json([...todos.values()]); }); app.post('/todos', (req, res) => { const result = todoInput.safeParse(req.body); if (!result.success) { throw new HttpError(400, 'Invalid input', z.flattenError(result.error).fieldErrors); } const todo = { id: nextId++, ...result.data }; todos.set(todo.id, todo); res.status(201).json(todo); }); // Errors thrown in an async handler also reach the error-handling middleware (Express 5) app.get('/todos/:id', async (req, res) => { const todo = todos.get(Number(req.params.id)); if (!todo) throw new HttpError(404, 'Todo not found'); res.json(todo); }); // Requests that matched no route app.use((req, res) => { res.status(404).json({ error: 'Route not found' }); }); // Error-handling middleware: it must take 4 arguments and be registered last app.use((err, req, res, next) => { const status = err.status ?? 500; if (status >= 500) console.error(err); res.status(status).json({ error: status >= 500 ? 'Internal server error' : err.message, details: err.details, }); }); return app;}
Run it and checkBASH
npm run devcurl -s -X POST localhost:3000/todos -H 'content-type: application/json' -d '{"title":"Read the guide"}'# {"id":1,"title":"Read the guide","done":false}curl -s -X POST localhost:3000/todos -H 'content-type: application/json' -d '{"title":" "}'# {"error":"Invalid input","details":{"title":["Too small: ..."]}}curl -s localhost:3000/todos/999# {"error":"Todo not found"}
Item
Express 4
Express 5
Errors in async handlers
Need try/catch and next(err)
Passed to the error middleware automatically
Wildcard paths
/files/*
/files/*name (a name is required)
Optional parameters
/users/:id?
/users{/:id}
Required Node.js
Supports old versions
18 or later
Configuration and environment variables
Here you look at Configuration and environment variables alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Values that differ per environment, such as the port, database address, and API keys, stay out of the code and come in as environment variables. The same code and the same image then run unchanged in development, staging, and production.
Environment variables are all strings, and a missing one raises no error. So validate once at startup and exit before taking requests when the configuration is wrong. A server that starts with bad configuration fails much later, somewhere unrelated.
Here you look at CPU work and Worker Threads alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Running long CPU-bound work on the main thread stops the event loop. worker_threads solves this by running JavaScript on a separate thread. Each worker has its own event loop and memory and exchanges data with the main thread through messages.
The example below moves a password hash computation to a worker. You can see the main thread's timer keep firing while the hash is computed.
hash-worker.jsJAVASCRIPT
import { parentPort, workerData } from 'node:worker_threads';import { pbkdf2Sync } from 'node:crypto';// Inside a worker, a sync function does not block the main threadconst hash = pbkdf2Sync(workerData.password, workerData.salt, 600_000, 32, 'sha256');parentPort.postMessage(hash.toString('hex'));
hash.jsJAVASCRIPT
import { Worker } from 'node:worker_threads';export function hashPassword(password, salt) { return new Promise((resolve, reject) => { const worker = new Worker(new URL('./hash-worker.js', import.meta.url), { workerData: { password, salt }, }); worker.once('message', resolve); worker.once('error', reject); worker.once('exit', (code) => { if (code !== 0) reject(new Error(`worker exited with code ${code}`)); }); });}const timer = setInterval(() => console.log('the event loop is still running'), 50);const hash = await hashPassword('secret', 'salt');clearInterval(timer);console.log(hash.slice(0, 16));
Approach
When to use
Watch out for
Worker Threads
CPU work that must finish within the request (hashing, image resizing)
Creating a worker has a cost, so reuse workers through a pool.
Job queue + separate process
Work that takes seconds or more (video conversion, bulk email)
Respond to the request with an acknowledgment and deliver the result later.
Multiple processes · replicas
When raising request throughput itself
In container environments, scale with the replica count.
Testing — node:test
Here you look at Testing — node:test alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Node.js includes a test runner (node:test) and an assertion module (node:assert). node --test finds and runs the test directory and *.test.js files. With nothing to install or configure, it is a sufficient default for a new project.
The test below starts the server on port 0 so the operating system picks a free port, then sends real HTTP requests with fetch. This works because app creation and server startup were separated earlier.
test/todos.test.jsJAVASCRIPT
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { createApp } from '../src/app.js';let server;let baseUrl;before(async () => { server = createApp().listen(0); // 0 = pick a free port automatically await new Promise((resolve) => server.once('listening', resolve)); baseUrl = `http://127.0.0.1:${server.address().port}`;});after(() => new Promise((resolve) => server.close(resolve)));test('creates a todo and reads it back', async () => { const created = await fetch(`${baseUrl}/todos`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'Read the guide' }), }); assert.equal(created.status, 201); const todo = await created.json(); assert.deepEqual(todo, { id: 1, title: 'Read the guide', done: false }); const found = await fetch(`${baseUrl}/todos/${todo.id}`); assert.equal(found.status, 200);});test('returns 400 when the title is empty', async () => { const res = await fetch(`${baseUrl}/todos`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: ' ' }), }); assert.equal(res.status, 400); const body = await res.json(); assert.ok(body.details.title);});test('returns 404 for a todo that does not exist', async () => { const res = await fetch(`${baseUrl}/todos/999`); assert.equal(res.status, 404);});
RunBASH
node --test# ✔ creates a todo and reads it back# ✔ returns 400 when the title is empty# ✔ returns 404 for a todo that does not exist# ℹ pass 3# ℹ fail 0node --test --watch # rerun when files changenode --test --test-name-pattern="404" # run only tests whose name matchesnode --test --experimental-test-coverage # print coverage
Operations — shutdown and logging
Here you look at Operations — shutdown and logging alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
On every deployment the existing process receives a termination signal (SIGTERM). If it dies right away, the requests in progress are cut off. A graceful shutdown stops accepting new connections, finishes the requests in progress, closes database connections and the like, and then exits. Kubernetes and Docker force-kill a process that does not finish within a time limit, so set a deadline as well.
Write logs to standard output as one JSON object per line, not as sentences for people to read. Collection tools can index them as they are, and you can search by field.
src/server.jsJAVASCRIPT
import { config } from './config.js';import { createApp } from './app.js';const app = createApp();const server = app.listen(config.PORT, () => { console.log(`running at http://localhost:${config.PORT}`);});function shutdown(signal) { console.log(`received ${signal}, shutting down`); // Stops accepting new connections; the callback runs once in-flight requests finish server.close((err) => { // Close database connection pools and the like here process.exit(err ? 1 : 0); }); server.closeIdleConnections(); // close keep-alive connections with no request right away // Force exit when it does not finish within 10 seconds setTimeout(() => process.exit(1), 10_000).unref();}process.on('SIGTERM', () => shutdown('SIGTERM'));process.on('SIGINT', () => shutdown('SIGINT'));
logger.js — structured logs with a request IDJAVASCRIPT
import { AsyncLocalStorage } from 'node:async_hooks';import { randomUUID } from 'node:crypto';const context = new AsyncLocalStorage();// Creates an ID per request that every async operation of that request can readexport function requestContext(req, res, next) { const requestId = req.get('x-request-id') ?? randomUUID(); res.set('x-request-id', requestId); context.run({ requestId }, next);}export function log(level, message, fields = {}) { console.log(JSON.stringify({ time: new Date().toISOString(), level, requestId: context.getStore()?.requestId, message, ...fields, }));}// Usage: app.use(requestContext); log('info', 'order lookup', { orderId: 42 });// {"time":"...","level":"info","requestId":"5fa4fa3a-...","message":"order lookup","orderId":42}
Operational item
What to check
Shutdown
On SIGTERM, does it finish in-flight requests and then exit?
Health checks
Are process liveness (/health) and dependency readiness (/ready) separate?
Logs
Are they written to standard output as JSON and do they include a request ID?
Timeouts
Do external calls and database queries have a time limit?
Unhandled errors
Are there no unhandled rejections, and if one occurs is it logged?
NODE_ENV
Is it set to production in production?
Deploying with Docker
Here you look at Deploying with Docker alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
An image for a Node.js application has three rules. Install dependencies before copying the source to keep the build cache, leave out development dependencies that production does not need, and run as a non-root user. The official image already includes a node user.
DockerfileDOCKERFILE
FROM node:24-slimENV NODE_ENV=productionWORKDIR /app# Copy only the dependency manifests first → this step is cached when only the source changesCOPY package.json package-lock.json ./RUN npm ci --omit=devCOPY src ./srcUSER nodeEXPOSE 3000# Run node directly, not npm start, so SIGTERM is deliveredCMD ["node", "src/server.js"]
.dockerignoreTEXT
node_modules
.env
.git
test
*.log
Build and runBASH
docker build -t todo-api:1.0 .docker run --rm -p 3000:3000 -e PORT=3000 --name todo-api todo-api:1.0# In another terminalcurl -s localhost:3000/healthdocker stop todo-api # SIGTERM → you should see the graceful shutdown log
Image tag
Characteristics
When to use
node:24-slim
Debian-based, essential packages only
Most services (recommended)
node:24-alpine
Smallest, uses musl libc
No native modules and size matters
node:24
Includes build tools, large
A build stage that compiles native modules
Diagnosing performance and memory
Here you look at Diagnosing performance and memory alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
When something feels slow, measure before changing code on a guess. Node.js includes a profiler and a debugger, so you can start without extra tools. What you look at depends on the symptom.
CPU profileBASH
# Records CPU usage while it runs. A .cpuprofile file is written on exitnode --cpu-prof src/server.js# In Chrome: chrome://inspect → Open dedicated DevTools for Node# → load the .cpuprofile file in the Performance tab and look for functions that took long
Debugger and heap snapshotsBASH
# Attach Chrome DevTools to the running processnode --inspect src/server.js# Take two heap snapshots in the Memory tab and compare them# (before and after applying load — objects that grew are leak candidates)# To write a heap snapshot file each time a signal arrivesnode --heapsnapshot-signal=SIGUSR2 src/server.js
Symptom
Suspect
How to check
Every request slows down together
Synchronous code blocking the event loop
monitorEventLoopDelay, --cpu-prof
Only certain requests are slow
Slow queries · external APIs
Per-request timing logs, database execution plans
Memory keeps growing
A memory leak (a Map · array · listeners that grow without end)
Compare two heap snapshots
CPU usage stays high
Repeated computation, heavy JSON processing, GC pressure
Read the profile from --cpu-prof
The process dies suddenly
An unhandled error, running out of memory
The last logs before exit, the exit code, whether it was OOMKilled
Security checklist
Here you look at Security checklist alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Security incidents in Node.js services come from dependencies and unvalidated input more often than from flaws in the framework. One project installs hundreds of packages, so managing what gets installed is the first line of defense.
Dependency checksBASH
npm audit # check for known vulnerabilitiesnpm audit fix # fix automatically within compatible rangesnpm outdated # check for outdated packagesnpm ls express # see through which path it was installed
Permission model — running with restricted file accessBASH
# Only the given directory can be read; other file reads · writes · child processes are blockednode --permission --allow-fs-read=/app src/server.js# Reading a path that was not allowed raises ERR_ACCESS_DENIED
Area
What to do
Dependencies
Commit the lockfile and install with npm ci in CI. Run npm audit regularly.
Choosing packages
Before installing, check the spelling of the name, maintenance status, and download counts. Malicious packages with similar names exist.
Input validation
Validate the body, query, and path parameters with a schema. Limit the body size.
Secrets
Keep them out of code and the repository. Inject them through environment variables or a secret manager.
SQL · command execution
Use parameter binding instead of concatenating strings. Do not put user input in shell commands.
HTTP headers
Turn off x-powered-by and set security headers with middleware such as helmet.
Rate limiting
Put a request limit on sensitive routes such as login.
Run privileges
Run as a non-root user. Do not use a Node.js version that has reached end of life.
Common errors
Common errors is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
Read the code in the error message (ERR_..., E...) first. The cause is mostly fixed for each one.
Error
Cause
Fix
EADDRINUSE: address already in use
Another process is using that port.
Stop the server you started earlier or use another port. Find the process with lsof -i :3000 (netstat -ano on Windows).
ERR_MODULE_NOT_FOUND
A relative import in ES Modules is missing its extension, or the package is not installed.
Write the extension, as in import './app.js', and check npm install.
Cannot use import statement outside a module
import was used in a file interpreted as CommonJS.
Add "type": "module" to package.json or change the file extension to .mjs.
ERR_REQUIRE_ESM
An old Node.js loaded an ES module package with require().
Upgrade Node.js to the latest LTS or switch to import.
JavaScript heap out of memory
The heap memory limit was exceeded.
Change code that loads large data into memory at once to streams, and check for leaks with heap snapshots. Adjust the limit with --max-old-space-size if needed.
ECONNREFUSED
Nothing is listening at the address you are connecting to.
Check that the target service is up and that the host and port are right. Inside a container, localhost is that container itself.
ECONNRESET · socket hang up
The other side closed the connection midway.
Check the other server's timeouts and whether it restarted, and add retries for safe requests.
EMFILE: too many open files
The number of files · sockets open at once exceeded the limit.
Limit how many files are opened at once and check for streams that are never closed.
ERR_HTTP_HEADERS_SENT
A response was sent twice for one request.
Check that the function returns after sending the response.
The process exits silently
An unhandled Promise rejection or exception
Look for async calls missing await and .catch(). Read the error log just before the exit.
Node.js practical design
Node.js practical design is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
The key in Node.js is a structure that does not block the event loop. Separate CPU work, I/O work, and background jobs, and make module boundaries clear.
Decision point
Question to ask
Practical guideline
Boundaries
Which parts of the Node.js code are most likely to change?
Separate input/output, configuration, external integrations, and the core rules.
State
Where is state created and where does it go away?
Make the owner and lifecycle of state visible in the code.
Failure
What does the caller receive on failure?
Decide the timeout, fallback, and error contract first.
Node.js operating standards
This section covers Node.js operating standards from a practical perspective. Instead of memorizing the concept, focus on the situations in which you would reach for it.
In operation, watch event loop delay, memory leaks, unhandled rejections, connection reuse, and graceful shutdown.
Node.js verification strategy
Node.js verification strategy is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
Include the API contract, async error handling, fake timers, and integration tests.
Quality axis
How to verify
Definition of done
Correctness
Automate the normal/failure cases.
The core scenarios pass reproducibly.
Regression prevention
When fixing a bug, leave the same case behind as a test.
The same failure is not deployed again.
Operability
Check the logs, metrics, and alerts.
There is a path for tracing the cause when a problem occurs.
Node.js: frequently asked questions
Node.js is single-threaded. How does it handle concurrent requests?
It does not hold a thread while waiting on network or file I/O; when the work completes, the event loop runs the callback. One thread can therefore serve many connections. The trade-off is that a long CPU-bound computation makes every other request wait.
How do I handle CPU-heavy work in Node.js?
Move it to Worker Threads, or split it into a separate process or job queue, so the event loop is not blocked. If image conversion or heavy computation is the core of the service, splitting that part into a service written in another language is also an option.
Should I use npm, yarn, or pnpm?
All three use the same package registry, so the functional differences are small. npm ships with Node.js, and pnpm is better on disk usage and install speed and has good monorepo support. What matters is that the team picks one, commits the lockfile, and does not mix them.
Next steps
Next steps is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
If you have come this far, you have followed the whole flow once: building an API server with Node.js, testing it, and deploying and operating it in a container. Widen out from here as you need.