Developed By Ken Key

Node.js Best Practices in 2026: A Practical Guide for Real Projects

By Ken Key Nov 26, 2024 6 min read Updated Oct 16, 2026

Node.js Best Practices in 2026: A Practical Guide for Real Projects
The short answer

Pin Node to an active LTS release (22 or 24 in 2026), enforce it with engines and .nvmrc, and use ESM with import.meta.url instead of dirname. Validate input, handle async errors, and never block the event loop. Those basics prevent most production failures I see.

Part of the complete web development guide.

On this page

Most Node.js advice online is either five years out of date or written by someone who has never had a service go down at 2am. This guide is the version I wish existed when I started shipping Node backends: the practices that actually matter in 2026, with code you can copy into a real project today.

I’ve been building Node services for years, from small client APIs to internal tools with real traffic. Everything below is something I’ve either used in production or watched someone regret skipping.

Pin your runtime and stay on an LTS line

Node 18 and 20 are both end-of-life now. If you’re starting fresh in 2026, build on Node 22 or 24 (both LTS). More importantly, pin the version explicitly so your laptop, CI, and production match. The classic “works on my machine” bug is usually a runtime version mismatch.

// package.json
{
 "engines": {
 "node": ">=22.0.0"
 }
}

Pair that with a .nvmrc file (or .node-version if you use fnm or asdf) so everyone on the team lands on the same binary. It takes ten seconds and saves hours.

Use ESM, but know what you’re getting into

ES modules are the default now. Top-level await works, import is the norm, and the ecosystem has largely caught up. That said, a few things still bite:

  • You can’t require() an ESM-only package from CommonJS without dynamic import().
  • __dirname and __filename don’t exist in ESM. Use import.meta.url.
  • JSON imports need an import attribute: import data from "./data.json" with { type: "json" }.
import { fileURLToPath } from "node:url";
import path from "node:path";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const configPath = path.join(__dirname, "config.json");

If you’re maintaining a big CommonJS codebase, don’t rewrite it for the sake of it. Migrate file by file, or keep it. Mixed setups are fine and Node handles them well.

Handle errors like they’re going to happen, because they will

The single biggest difference between a hobby project and a production service is what happens when something throws. Unhandled promise rejections and uncaught exceptions should never silently kill your process without a log.

process.on("unhandledRejection", (reason) => {
 console.error("Unhandled rejection:", reason);
 // In a real service: report to your error tracker, then exit
 process.exitCode = 1;
});

process.on("uncaughtException", (err) => {
 console.error("Uncaught exception:", err);
 // The process is in an unknown state. Log, report, exit.
 process.exit(1);
});

Two things people get wrong here. First, don’t try to keep running after an uncaughtException. The process state is unpredictable. Log it, report it, let your process manager restart it. Second, use a process manager or orchestrator: systemd, PM2, Docker with a restart policy, Kubernetes, whatever fits. Node should not be responsible for resurrecting itself.

Distinguish operational errors from programmer errors

Operational errors (network timeout, bad user input, a 404 from an upstream API) are expected. Handle them at the boundary and return a sensible response. Programmer errors (undefined is not a function, typos in your own code) mean something is broken and you should fail loudly. Treating both the same way is how you end up with services that “work” while quietly returning garbage.

Structure your project so you can find things

There’s no single correct layout, but there is a wrong one: everything in one index.js. A layout that scales for most teams looks like this:

src/
 routes/ // HTTP route definitions
 services/ // business logic, no HTTP knowledge
 repositories/ // database access
 lib/ // shared utilities
 config/ // env parsing and validation
 server.js // wires it together

The key rule: keep your business logic out of your route handlers. When a route handler is 200 lines long, testing and reusing it becomes painful. Push logic into services, keep handlers thin. When I do custom web development for clients, this separation is the thing that keeps a codebase maintainable a year later when requirements change.

Validate everything that crosses a boundary

Environment variables, request bodies, query params, upstream API responses. If data comes from outside your code, validate it. Zod is the pragmatic choice in 2026, but Joi, Ajv, and TypeBox all work.

import { z } from "zod";

const EnvSchema = z.object({
 PORT: z.coerce.number().default(3000),
 DATABASE_URL: z.string().url(),
 NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
});

const env = EnvSchema.parse(process.env);
export default env;

This fails fast at startup if config is missing, instead of failing at 3am when a request finally hits the code path that needs that variable. Same principle for request bodies: parse, don’t trust.

Don’t block the event loop

Node’s whole model depends on the event loop staying free. Synchronous file reads, CPU-heavy loops, and big JSON serialization in a request path will stall every other request. If you need to do heavy computation, move it off the main thread with worker_threads, or off the process entirely with a job queue.

import { Worker } from "node:worker_threads";

function runHeavyTask(data) {
 return new Promise((resolve, reject) => {
 const worker = new Worker(new URL("./worker.js", import.meta.url), {
 workerData: data,
 });
 worker.on("message", resolve);
 worker.on("error", reject);
 worker.on("exit", (code) => {
 if (code !== 0) reject(new Error(`Worker stopped with code ${code}`));
 });
 });
}

For anything that can wait (sending emails, generating reports, resizing images), push it to a queue and process it in a separate worker service. BullMQ with Redis is still the standard answer here, and it holds up.

Security basics that people still skip

  • Run npm audit in CI and actually read the output. Not every alert is real, but the ones that are matter.
  • Set security headers. Helmet handles most of this in one line.
  • Rate limit your public endpoints. express-rate-limit or a reverse proxy rule. Unprotected login endpoints get hammered.
  • Never log secrets. Sanitize what you send to your logger. API keys, tokens, and passwords should never appear in logs.
  • Use parameterized queries. String-concatenated SQL is still the most common way Node apps get owned.
import helmet from "helmet";
import rateLimit from "express-rate-limit";

app.use(helmet());
app.use("/api/", rateLimit({ windowMs: 60_000, limit: 100 }));

Log in structured form, from day one

console.log("got here") is fine while you’re building. It’s useless when you’re debugging a production incident across three services. Use a structured logger (pino is fast and everywhere) and log JSON with a request ID so you can trace a single request through the system.

import pino from "pino";

const logger = pino({ level: process.env.LOG_LEVEL || "info" });

logger.info({ requestId, userId, route: req.path }, "request received");

Once you have request IDs flowing through, debugging stops being guesswork.

Test the things that break

You don’t need 100% coverage. You need tests around the logic that would hurt if it broke: money calculations, auth checks, data transforms, anything with a branch. Node’s built-in test runner (node:test) is genuinely good now and removes a dependency. Vitest is the other solid choice, especially if you’re already using Vite elsewhere.

import { test } from "node:test";
import assert from "node:assert/strict";
import { calculateTotal } from "../src/services/pricing.js";

test("applies discount before tax", () => {
 const total = calculateTotal({ subtotal: 100, discount: 10, taxRate: 0.08 });
 assert.equal(total, 97.2);
});

Wrap up

None of this is exotic. Pin your runtime, use ESM where it makes sense, handle errors deliberately, validate at the boundaries, keep the event loop free, and log in a form you can actually search. Do those and you’re ahead of most Node codebases in production right now. The rest is optimization.

FAQ

Should I use Express, Fastify, or the built-in HTTP module in 2026?

For most apps, Fastify. It’s faster than Express, has schema validation built in, and the plugin system is clean. Express 5 is fine and familiar if you’re maintaining an existing app. The raw HTTP module is worth knowing but rarely the right choice for an API with real routing needs.

Do I still need a process manager if I’m using Docker?

No, Docker’s restart policy handles that. What you still need is graceful shutdown: catch SIGTERM, stop accepting new connections, finish in-flight requests, close your database pool, then exit. Otherwise every deploy drops requests.

How do I know if my Node app is blocking the event loop?

Measure it. The perf_hooks module has a built-in event loop delay monitor, and tools like Clinic.js will show you exactly which functions are hogging the loop. If you’re guessing, you’re probably wrong about where the problem is.

Have a project like this?

I do custom web development for Long Island businesses. If you need this done right, let’s talk.