Skip to main content
AIDevOps
  • Learn
  • Learning Paths
  • Practice
  • Open Source
  • Books
  • Engineering

    AI DevOpsThe full map of building and operating AI servicesLLMOpsLLM deployment · evaluation · observabilityHands-on ProjectsBuild AI Agent projects

    Knowledge

    DocsTechnical documentationBlogEngineering articlesPloggerDevelopment log feed

    Validate

    Certification3-level skills certification · coming soon
AI Models
LlamaTutorial|MistralTutorial|GemmaTutorial|DeepSeekTutorial|QwenTutorial
⚙️ Backend
Backend Intro & RoadmapPython BasicsFastAPIDjangoFlask|CGoGinNode.js
🤖 AI Applied Development
Applied AI Intro & RoadmapHugging FaceLangChainLlamaIndexLLMOps|LangGraphMCPMulti-AgentAgent Evaluation
🧠 AI Core
AI Intro & RoadmapML FundamentalsLLM Fundamentals|Python AIC++|PyTorchTensorFlowJAX
🧠 AI Agent Development
Finance AI AgentLLM API ServerStock Investing AgentAIOps AI AgentEducation AI AgentCoding AI Agent
🌱 Spring Cloud
Spring Intro & RoadmapSpring Cloud GatewaySpring BootJava|Spring AISpring SecuritySpring BatchSpring JPA
🐳 DevOps
DevOps Intro & RoadmapLinuxDockerCI/CD|Kubernetes BasicsK8s AdvancedPrometheusGrafana
🧱 Infrastructure
Infrastructure Intro & RoadmapNginxRedis
☁️ Cloud
Cloud Intro & RoadmapAWSGCPAzureNCPCloudflare
🎨 Frontend
Frontend Intro & RoadmapJavaScriptTypeScript|ReactNext.js|VueNuxt|Electron
📱 Mobile
Mobile Intro & RoadmapKotlinAndroidFlutter
💾 Database
DB Intro & RoadmapCore SQLOracleMySQLPostgreSQL|MongoDBVector DB
🧪 Testing
k6JMeternGrinder
AIDevOps

Engineering AI. From Code to Production.
An engineering learning platform for building and operating AI and AI Agents

Learn

  • All Guides
  • Learning Paths
  • AI Tutorial
  • Practice
  • Books

Resources

  • AI DevOps
  • LLMOps
  • Hands-on Projects
  • Docs
  • Blog
  • Plogger
  • Open Source
  • Certification (coming soon)

Start Here

  • AI Core Roadmap
  • AI Applied Development Roadmap
  • Spring Cloud Roadmap
  • DevOps Roadmap
  • Infrastructure Roadmap

 

  • Cloud Roadmap
  • Frontend Roadmap
  • Mobile Roadmap
  • Backend Roadmap
  • Database Roadmap
© 2026 AIDevOps. All rights reserved.
Terms of ServicePrivacy PolicySitemaptestforge.kr
  1. Home
  2. Learn
  3. Backend
  4. Node.js
Node.js 24 LTS Server Development Guide

🟢 Node.js Complete Guide

Visitors

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.

Open the Web IDE →
Express 5 API serverEvent loop and asyncBuilt-in test runnerDocker deployment and operationsPerformance diagnostics

Related frameworks & environments

✨JavaScript→🔷TypeScript→🖥️Electron→▲Next.js→

Contents

0 / 25
  1. How to use this guide
  2. Architecture diagrams
  3. What is Node.js?
  4. Choosing a version and installing
  5. npm & package.json
  6. ES Modules vs CommonJS
  7. Built-in tools — watch · env · test · TypeScript
  8. Event loop & async
  9. Async error handling and timeouts
  10. File system and streams
  11. HTTP server and fetch
  12. Building an API server with Express 5
  13. Configuration and environment variables
  14. CPU work and Worker Threads
  15. Testing — node:test
  16. Operations — shutdown and logging
  17. Deploying with Docker
  18. Diagnosing performance and memory
  19. Security checklist
  20. Common errors
  21. Node.js design
  22. Operating standards
  23. Verification strategy
  24. Frequently asked questions
  25. Next steps
Contents 25 sections
  1. How to use this guide
  2. Architecture diagrams
  3. What is Node.js?
  4. Choosing a version and installing
  5. npm & package.json
  6. ES Modules vs CommonJS
  7. Built-in tools — watch · env · test · TypeScript
  8. Event loop & async
  9. Async error handling and timeouts
  10. File system and streams
  11. HTTP server and fetch
  12. Building an API server with Express 5
  13. Configuration and environment variables
  14. CPU work and Worker Threads
  15. Testing — node:test
  16. Operations — shutdown and logging
  17. Deploying with Docker
  18. Diagnosing performance and memory
  19. Security checklist
  20. Common errors
  21. Node.js design
  22. Operating standards
  23. Verification strategy
  24. Frequently asked questions
  25. Next steps

How to use this guide

How to read it

Understanding Node.js as a real-world workflow

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.

SituationFitWhy
REST · GraphQL API serversGoodMost of each request is I/O: waiting on the database and external APIs.
Real-time services (chat, notifications, streaming)GoodMany connections are kept open with few resources.
BFF, API gatewayGoodCombines several APIs in the same language as the frontend.
CLI tools, build scriptsGoodThe npm ecosystem and fast startup are advantages.
Image · video conversion, heavy computationCautionIt blocks the event loop. Move it to Worker Threads or a separate service.
Model training · numerical computingPoorPython's scientific computing ecosystem is far richer.

Tip

The question for choosing Node.js is not "is it a fast language" but "does the work spend most of its time waiting". The more waiting there is, the more the Node.js design helps.

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 nvm
nvm install 24        # install 24 LTS
nvm use 24
node --version        # v24.x.x
npm --version
Windows · macOS · Linux (fnm)BASH
# fnm works with the same commands on Windows too
fnm install 24
fnm use 24
node --version
Pin the version in the projectBASH
# Write the version to use at the repository root
echo "24" > .nvmrc

# After that, no version number is needed
nvm use               # or fnm use
Release statusMeaningUse on servers
CurrentThe version receiving the newest features. Even-numbered versions become LTS in October.No
Active LTSA long-term support version that receives both new features and bug fixesYes (recommended)
Maintenance LTSSecurity and critical bug fixes onlyYes (plan the upgrade)
End-of-LifeSecurity patches have endedNo

Tip

  • Writing "node": ">=24" in the engines field of package.json produces a warning when someone installs with a version that does not match.
  • Keep the Node.js major version the same locally, in CI, and in the Docker image. Different versions are how "it works on my machine" happens.

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.

package.jsonJSON
{
  "name": "todo-api",
  "version": "1.0.0",
  "type": "module",
  "engines": { "node": ">=24" },
  "scripts": {
    "dev": "node --watch --env-file=.env src/server.js",
    "start": "node src/server.js",
    "test": "node --test"
  },
  "dependencies": {
    "express": "^5.2.0",
    "zod": "^4.0.0"
  }
}
Common commandsBASH
npm install express zod      # add dependencies
npm install -D typescript    # add a development dependency
npm ci                       # install exactly what the lockfile says (CI · Docker)
npm outdated                 # see which packages can be updated
npm audit                    # check for known vulnerabilities
npm run dev                  # run the dev script
NotationAllowed rangeExample
^5.2.0Latest version with the same major (minor · patch updates)5.2.0 or later, below 6.0.0
~5.2.0Latest version with the same minor (patch updates only)5.2.0 or later, below 5.3.0
5.2.0Exactly that version5.2.0

Tip

  • Always commit package-lock.json to the repository. Teammates, CI, and production servers then install the same versions.
  • Once you pick npm, pnpm, or yarn, do not mix them. Their lockfiles differ, so installs drift apart.

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: prefix
import express from 'express';                  // npm package
import { createApp } from './app.js';           // your own files need the extension

export function helper() {}                     // named export
export default createApp;                       // default export

// await works at the top level
const text = await readFile(new URL('./data.json', import.meta.url), 'utf8');

console.log(import.meta.dirname);               // directory of this file
console.log(import.meta.filename);              // absolute path of this file
CommonJS (what you see in existing projects)JAVASCRIPT
const { readFile } = require('node:fs/promises');
const express = require('express');

module.exports = { helper };

console.log(__dirname);
ItemES ModulesCommonJS
Declared by"type": "module" in package.json, or .mjsThe default, or .cjs
Importingimport x from "./x.js"const x = require("./x")
ExtensionRequired for relative pathsOptional
Current pathimport.meta.dirname__dirname
Top-level awaitYesNo
Importing JSONimport data from "./a.json" with { type: "json" }require("./a.json")

Tip

In recent Node.js, CommonJS code can load ES module packages with require() (only modules without top-level await). The ERR_REQUIRE_ESM error that appears in older articles is mostly solved by upgrading Node.js.

Built-in tools — watch · env · test · TypeScript

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 variables
node --watch --env-file=.env src/server.js

# To continue without an error when there is no .env file
node --env-file-if-exists=.env src/server.js
greet.tsTYPESCRIPT
interface User {
  name: string;
  age?: number;
}

function greet(user: User): string {
  return `Hello, ${user.name}`;
}

console.log(greet({ name: 'Mina' }));
Run TypeScript directlyBASH
node greet.ts
# Hello, Mina

# Type checking is a separate step
npx tsc --noEmit
What you wantPackage used beforeBuilt in
Restart when files changenodemonnode --watch src/server.js
Read a .env filedotenvnode --env-file=.env src/server.js
Run testsjest, mochanode --test
HTTP requestsaxios, node-fetchglobal fetch
Run TypeScriptts-node, tsxnode app.ts
Parse argumentsyargs, commanderutil.parseArgs
Generate UUIDsuuidcrypto.randomUUID()

Tip

  • Node.js runs TypeScript by stripping the type annotations; it does not type-check. Catch type errors with tsc --noEmit or in the editor.
  • Syntax that has to be transformed into JavaScript code, such as enum and namespace, is not supported by default. Write type-only code or add a build step.
  • A .env file holds secrets, so add it to .gitignore and commit a .env.example that lists only the keys that are needed.

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 time
function 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 loopWhat to use instead
Sync functions such as readFileSync while handling a requestThe async functions in fs/promises
JSON.parse / stringify on a large JSON in one goA streaming parser, processing page by page
Sorting · looping over a large arrayWorker Threads, a job queue
Synchronous crypto (pbkdf2Sync, sync bcrypt functions)The async functions, or Worker Threads
Regular expressions that slow down sharply with input lengthLimit input length, use simpler patterns

Tip

  • Be suspicious when synchronous code takes tens of milliseconds or more while handling one request. Every other request is delayed by that much.
  • Sync functions that run once before requests are served, such as reading a config file at startup, are fine.

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 terminates

setTimeout(() => 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 fails
const 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/...
FunctionBehaviorWhen to use
Promise.allFails immediately when any one failsWhen it only makes sense if all succeed
Promise.allSettledWaits for all and returns each resultWhen some failures are acceptable
Promise.raceReturns the first result to settle (success · failure)When implementing a timeout yourself
Promise.anyReturns the first successWhen one of several mirrors succeeding is enough

Tip

  • fetch does not throw on a 404 or 500 response. You have to check res.ok yourself.
  • Awaiting independent tasks one by one adds their times together. Wait for them together with Promise.all.
  • Starting thousands of tasks at once with Promise.all exhausts the other server or the database connections. Limit how many run concurrently.

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).

files.js — small filesJAVASCRIPT
import { readFile, writeFile, mkdir, readdir } from 'node:fs/promises';
import { join } from 'node:path';

const dir = join(import.meta.dirname, 'data');
await mkdir(dir, { recursive: true });

await writeFile(join(dir, 'config.json'), JSON.stringify({ port: 3000 }, null, 2));
const config = JSON.parse(await readFile(join(dir, 'config.json'), 'utf8'));

console.log(config.port, await readdir(dir));
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 size
await 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);

Tip

  • Build paths with path.join rather than concatenating strings. The separator differs between operating systems.
  • Using a file name sent by a user directly in a path lets ../ reach parent directories. Keep only the file name with path.basename or check it against an allowlist.

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
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/health') {
    res.writeHead(200, { 'content-type': 'application/json' });
    res.end(JSON.stringify({ status: 'ok' }));
    return;
  }
  res.writeHead(404).end();
});

server.listen(3000, () => console.log('http://localhost:3000'));
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());

Tip

Code that calls another service has to handle slow responses, error responses, and dropped connections. Apply retries only to work that is safe to send twice, such as reads.

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 validation
const 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 dev

curl -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"}
ItemExpress 4Express 5
Errors in async handlersNeed 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.jsSupports old versions18 or later

Tip

  • Keep the details of a 500 error (stack, database error message) out of the response and in the logs only. They expose your internals as they are.
  • Do not write business logic directly in handlers; move it to functions or service modules. It can then be tested without HTTP.
  • As the app grows, split route files by area, such as /todos and /users, with express.Router().

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.

.env (not committed to the repository)BASH
PORT=3000
LOG_LEVEL=info
src/config.jsJAVASCRIPT
import { z } from 'zod';

const schema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().min(1).max(65535).default(3000),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
});

const parsed = schema.safeParse(process.env);
if (!parsed.success) {
  console.error('Invalid environment variables:', z.flattenError(parsed.error).fieldErrors);
  process.exit(1);
}

export const config = parsed.data;
Starting with a bad valueBASH
PORT=abc node src/server.js
# Invalid environment variables: { PORT: [ 'Invalid input: expected number, received NaN' ] }
# (exit code 1)

Tip

  • Do not read process.env all over the code; read it in one config module. What configuration the app needs is then visible at a glance.
  • In production, inject values through the deployment platform's environment variables or secrets rather than a .env file.

CPU work and Worker Threads

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 thread
const 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));
ApproachWhen to useWatch out for
Worker ThreadsCPU 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 processWork that takes seconds or more (video conversion, bulk email)Respond to the request with an acknowledgment and deliver the result later.
Multiple processes · replicasWhen raising request throughput itselfIn container environments, scale with the replica count.

Tip

  • Creating a new worker per request makes things slower. In practice a worker pool library reuses workers created ahead of time.
  • Moving I/O work to a worker does not make it faster. Workers are for CPU work only.

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 0

node --test --watch                          # rerun when files change
node --test --test-name-pattern="404"        # run only tests whose name matches
node --test --experimental-test-coverage     # print coverage

Tip

  • Do not test only the happy path; include failure paths such as invalid input, missing resources, and missing permissions. Most real incidents come from failure paths.
  • Tests do not call external APIs for real. Have the calling function injected so a test can replace it with a fake.
  • If you need snapshots, rich mocking, or a browser environment, look at a tool such as Vitest.

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 read
export 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 itemWhat to check
ShutdownOn SIGTERM, does it finish in-flight requests and then exit?
Health checksAre process liveness (/health) and dependency readiness (/ready) separate?
LogsAre they written to standard output as JSON and do they include a request ID?
TimeoutsDo external calls and database queries have a time limit?
Unhandled errorsAre there no unhandled rejections, and if one occurs is it logged?
NODE_ENVIs it set to production in production?

Tip

  • For a service with many requests, use a logging library such as pino instead of console.log. Serialization is fast, and it supports log levels and redacting sensitive data.
  • Do not log passwords, tokens, or national ID numbers. Code that writes the whole request body to the log is the most common leak.
  • In Docker, write CMD so it runs node directly, as in ["node", "src/server.js"]. Started through npm start, the termination signal may not reach the node process.

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-slim

ENV NODE_ENV=production
WORKDIR /app

# Copy only the dependency manifests first → this step is cached when only the source changes
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

COPY src ./src

USER node
EXPOSE 3000

# Run node directly, not npm start, so SIGTERM is delivered
CMD ["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 terminal
curl -s localhost:3000/health
docker stop todo-api          # SIGTERM → you should see the graceful shutdown log
Image tagCharacteristicsWhen to use
node:24-slimDebian-based, essential packages onlyMost services (recommended)
node:24-alpineSmallest, uses musl libcNo native modules and size matters
node:24Includes build tools, largeA build stage that compiles native modules

Tip

  • Without node_modules in .dockerignore, the packages installed locally are copied into the image and binaries for a different operating system get mixed in.
  • For a project that builds TypeScript, a multi-stage build separates the build stage from the runtime stage so the compiler does not stay in the image.
  • When you set a memory limit on the container, observe real usage and leave headroom. As the heap nears the limit, the container is killed (OOMKilled).

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 exit
node --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 process
node --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 arrives
node --heapsnapshot-signal=SIGUSR2 src/server.js
SymptomSuspectHow to check
Every request slows down togetherSynchronous code blocking the event loopmonitorEventLoopDelay, --cpu-prof
Only certain requests are slowSlow queries · external APIsPer-request timing logs, database execution plans
Memory keeps growingA memory leak (a Map · array · listeners that grow without end)Compare two heap snapshots
CPU usage stays highRepeated computation, heavy JSON processing, GC pressureRead the profile from --cpu-prof
The process dies suddenlyAn unhandled error, running out of memoryThe last logs before exit, the exit code, whether it was OOMKilled

Tip

  • --inspect opens a port that can execute code. It must not be exposed publicly in production. Keep it on 127.0.0.1, the default, and connect through port forwarding when needed.
  • Common causes of memory leaks are caches (Map) that pile up without expiry, event listeners that are never removed, and code that keeps appending to a global array.
  • Optimize only what the profile shows is actually taking time. Places fixed on a guess are usually not the bottleneck.

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 vulnerabilities
npm audit fix                # fix automatically within compatible ranges
npm outdated                 # check for outdated packages
npm 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 blocked
node --permission --allow-fs-read=/app src/server.js

# Reading a path that was not allowed raises ERR_ACCESS_DENIED
AreaWhat to do
DependenciesCommit the lockfile and install with npm ci in CI. Run npm audit regularly.
Choosing packagesBefore installing, check the spelling of the name, maintenance status, and download counts. Malicious packages with similar names exist.
Input validationValidate the body, query, and path parameters with a schema. Limit the body size.
SecretsKeep them out of code and the repository. Inject them through environment variables or a secret manager.
SQL · command executionUse parameter binding instead of concatenating strings. Do not put user input in shell commands.
HTTP headersTurn off x-powered-by and set security headers with middleware such as helmet.
Rate limitingPut a request limit on sensitive routes such as login.
Run privilegesRun as a non-root user. Do not use a Node.js version that has reached end of life.

Tip

  • npm packages can run scripts at install time. When trying out a package you do not trust, install it with npm install --ignore-scripts.
  • Do not return stack traces or SQL statements in error responses. They tell an attacker about your internals.

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.

ErrorCauseFix
EADDRINUSE: address already in useAnother 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_FOUNDA 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 moduleimport was used in a file interpreted as CommonJS.Add "type": "module" to package.json or change the file extension to .mjs.
ERR_REQUIRE_ESMAn 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 memoryThe 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.
ECONNREFUSEDNothing 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 upThe 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 filesThe 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_SENTA response was sent twice for one request.Check that the function returns after sending the response.
The process exits silentlyAn unhandled Promise rejection or exceptionLook for async calls missing await and .catch(). Read the error log just before the exit.

Tip

When an error occurs, read the whole message and the first line of the stack that is "your code". Lines inside node_modules are usually the result, not the cause.

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 pointQuestion to askPractical guideline
BoundariesWhich parts of the Node.js code are most likely to change?Separate input/output, configuration, external integrations, and the core rules.
StateWhere is state created and where does it go away?Make the owner and lifecycle of state visible in the code.
FailureWhat 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.

Tip

  • event loop delay
  • graceful shutdown
  • unhandled rejection
  • contract tests

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 axisHow to verifyDefinition of done
CorrectnessAutomate the normal/failure cases.The core scenarios pass reproducibly.
Regression preventionWhen fixing a bug, leave the same case behind as a test.The same failure is not deployed again.
OperabilityCheck 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.

What you want to doGuide to read next
Make code safer with typesTypeScript guide
Understand the language more deeplyJavaScript guide
Connect a databasePostgreSQL guide · Common SQL guide
Add a cache and session storeRedis guide
Package and deploy with containersDocker guide · Kubernetes guide
Automate deploymentCI/CD guide
Collect metrics and monitorPrometheus guide · Grafana guide
Build the UI as wellNext.js guide
Build a desktop appElectron guide

Tip

Rather than adding several tools at once, the best next exercise is to connect one database to this guide's Todo API and take it through testing and deployment again.

← Previous guideGin