API Development with Node.js and Express: Complete Guide 2025

Express is still the most common way to build HTTP APIs in Node.js, and with Express 5 now the stable release line, it's a solid, modern foundation rather than a legacy choice. This guide walks through building a production-ready REST API: project structure, resource design, validation, error handling, authentication, security middleware, logging, documentation, testing, and deployment. All examples use ES modules and current Express 5 behavior.
What Changed in Express 5
Express 5.0 was released in late 2024 after a long development cycle, and it's now the default version installed from npm. It requires Node.js 18 or newer. The changes that matter most day to day:
- Async error handling. If a route handler or middleware returns a rejected promise (for example, an
asyncfunction that throws), Express 5 forwards the error to your error-handling middleware automatically. You no longer needtry/catchwrappers or packages likeexpress-async-errorsjust to avoid unhandled rejections. - New path syntax. Express 5 uses an updated version of
path-to-regexp. Wildcards must be named (/files/*splatinstead of/files/*), optional segments use braces (/users{/:id}instead of/users/:id?), and regular-expression characters inside string paths are no longer supported. req.queryis read-only. It's now a getter, so middleware that assigned a new object toreq.querywill break. Store parsed values elsewhere, such asres.locals.req.bodyisundefinedwhen no body parser has run, rather than an empty object.- Removed legacy APIs, such as
app.del()(useapp.delete()) andres.send(status, body)signatures (useres.status(code).send(body)).
If you're upgrading from Express 4, read the official migration guide and check wildcard routes and optional parameters first.
Project Structure
A small, predictable structure makes an API easier to test and grow. Separating the Express app from the code that starts the server is the most useful single decision, because tests can import the app without opening a port.
api/
src/
app.js # builds and exports the Express app
server.js # starts the HTTP server, handles shutdown
config.js # reads and validates environment variables
db.js # database client/pool
routes/
projects.js
middleware/
validate.js
errors.js
auth.js
services/
projects.js # business logic and database access
test/
projects.test.js
package.json
Set "type": "module" in package.json so .js files are treated as ES modules:
{
"name": "api",
"type": "module",
"engines": { "node": ">=22" },
"scripts": {
"dev": "node --watch --env-file=.env src/server.js",
"start": "node src/server.js",
"test": "node --test"
}
}
Built-in --watch and --env-file flags replace nodemon and dotenv for most projects.
Designing RESTful Resources
Good API design is mostly consistency: clients should be able to guess how an endpoint behaves.
Resources and methods
Use plural nouns for collections and let HTTP methods express the action:
| Method | Path | Purpose | Success status |
|---|---|---|---|
| GET | /v1/projects | List projects | 200 |
| POST | /v1/projects | Create a project | 201 (+ Location header) |
| GET | /v1/projects/:id | Fetch one project | 200 |
| PATCH | /v1/projects/:id | Partially update | 200 |
| DELETE | /v1/projects/:id | Delete | 204 |
Status codes that matter
- 400 Bad Request for malformed or invalid input (some APIs use 422 for semantically invalid data; pick one and be consistent).
- 401 Unauthorized when authentication is missing or invalid.
- 403 Forbidden when the user is authenticated but not allowed.
- 404 Not Found for missing resources, or ones the user shouldn't know exist.
- 409 Conflict for duplicates or version conflicts.
- 429 Too Many Requests when rate limited.
- 500 Internal Server Error for unexpected failures, without leaking stack traces.
Practical conventions
- Version the API in the path (
/v1) or a header, so you can make breaking changes later. - Paginate list endpoints. Cursor-based pagination (
?cursor=...&limit=20) holds up better than offsets on large, changing tables. - Use one error format everywhere, for example
{ "error": { "code": "validation_failed", "message": "...", "details": [] } }. RFC 9457 (Problem Details for HTTP APIs) is a standard option. - Use consistent naming and ISO 8601 timestamps in UTC.
The database behind these endpoints matters as much as the routes; our database design and optimization guide covers indexing and query patterns for APIs like this.
Validation With Zod
Never trust request data. A schema library like Zod lets you validate and parse input in one step and get typed, cleaned values back.
// src/middleware/validate.js
export function validate(schemas) {
return (req, res, next) => {
const parsed = {};
for (const part of ["body", "query", "params"]) {
if (!schemas[part]) continue;
const result = schemas[part].safeParse(req[part]);
if (!result.success) {
return res.status(400).json({
error: {
code: "validation_failed",
message: "Invalid " + part,
details: result.error.issues.map((i) => ({
path: i.path.join("."),
message: i.message,
})),
},
});
}
parsed[part] = result.data;
}
res.locals.input = parsed;
next();
};
}
Because req.query is read-only in Express 5, the parsed values go in res.locals.input instead of overwriting the request.
// src/routes/projects.js
import { Router } from "express";
import { z } from "zod";
import { validate } from "../middleware/validate.js";
import * as projects from "../services/projects.js";
const router = Router();
const createProject = z.object({
name: z.string().trim().min(1).max(120),
budget: z.number().int().nonnegative().optional(),
});
const listQuery = z.object({
limit: z.coerce.number().int().min(1).max(100).default(20),
cursor: z.string().optional(),
});
router.get("/", validate({ query: listQuery }), async (req, res) => {
const { limit, cursor } = res.locals.input.query;
res.json(await projects.list({ ownerId: req.user.id, limit, cursor }));
});
router.post("/", validate({ body: createProject }), async (req, res) => {
const project = await projects.create(req.user.id, res.locals.input.body);
res.status(201).location("/v1/projects/" + project.id).json(project);
});
router.get("/:id", async (req, res) => {
const project = await projects.findForUser(req.params.id, req.user.id);
if (!project) return res.status(404).json({ error: { code: "not_found", message: "Project not found" } });
res.json(project);
});
export default router;
Note that the handlers are async with no try/catch. In Express 5, a thrown error or rejected promise goes straight to the error handler. Also note the ownership check in findForUser: always scope queries to the current user rather than fetching by ID alone.
Centralized Error Handling
Define a small error class for expected failures, and one error-handling middleware (four arguments) registered last:
// src/middleware/errors.js
export class HttpError extends Error {
constructor(status, code, message) {
super(message);
this.status = status;
this.code = code;
}
}
export function notFound(req, res) {
res.status(404).json({ error: { code: "not_found", message: "Route not found" } });
}
export function errorHandler(err, req, res, next) {
if (res.headersSent) return next(err);
const status = err.status && err.status < 500 ? err.status : 500;
if (status === 500) req.log.error({ err }, "unhandled error");
res.status(status).json({
error: {
code: err.code || (status === 500 ? "internal_error" : "error"),
message: status === 500 ? "Something went wrong" : err.message,
},
});
}
Clients get a consistent shape, and internal details stay in your logs.
Authentication: Sessions vs. JWTs
There's no universal winner; choose based on your clients.
- Session cookies are the simplest secure option when your API serves your own web front end on the same site. The server stores session state (in Redis or a database), the browser holds an opaque ID in an
HttpOnly,Secure,SameSitecookie, and revoking a session is just deleting it. You'll need CSRF protection for state-changing requests. - JWTs (bearer tokens) suit mobile apps, third-party clients, and service-to-service calls. They're stateless to verify, but that's also their weakness: you can't easily revoke one before it expires.
If you use JWTs, keep access tokens short-lived (minutes, not days), pair them with a longer-lived refresh token that is stored securely and rotated on each use, and always verify the algorithm, issuer, audience, and expiry. The jose library is a well-maintained choice:
// src/middleware/auth.js
import { jwtVerify } from "jose";
import { config } from "../config.js";
import { HttpError } from "./errors.js";
const secret = new TextEncoder().encode(config.JWT_SECRET);
export async function requireAuth(req, res, next) {
const header = req.get("authorization") || "";
const [scheme, token] = header.split(" ");
if (scheme !== "Bearer" || !token) throw new HttpError(401, "unauthorized", "Missing token");
try {
const { payload } = await jwtVerify(token, secret, {
algorithms: ["HS256"],
issuer: "api.example.com",
audience: "example-app",
});
req.user = { id: payload.sub, role: payload.role };
} catch {
throw new HttpError(401, "unauthorized", "Invalid or expired token");
}
next();
}
Because this middleware is async, throwing inside it is handled by Express 5 just like a route handler. Don't put sensitive data in a JWT payload; it's encoded, not encrypted. For a broader look at passwords, passkeys, and cookie settings, see our web security best practices guide.
Security Middleware: Helmet, CORS, and Rate Limiting
Here's an app.js that ties it together:
// src/app.js
import express from "express";
import helmet from "helmet";
import cors from "cors";
import { rateLimit } from "express-rate-limit";
import pinoHttp from "pino-http";
import { config } from "./config.js";
import { requireAuth } from "./middleware/auth.js";
import { notFound, errorHandler } from "./middleware/errors.js";
import projectsRouter from "./routes/projects.js";
export function createApp() {
const app = express();
app.disable("x-powered-by");
app.set("trust proxy", 1); // behind one reverse proxy / load balancer
app.use(pinoHttp({ redact: ["req.headers.authorization", "req.headers.cookie"] }));
app.use(helmet());
app.use(cors({ origin: config.CORS_ORIGINS, credentials: true }));
app.use(express.json({ limit: "100kb" }));
app.get("/healthz", (req, res) => res.json({ status: "ok" }));
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 300,
standardHeaders: "draft-8",
legacyHeaders: false,
});
app.use("/v1", apiLimiter, requireAuth);
app.use("/v1/projects", projectsRouter);
app.use(notFound);
app.use(errorHandler);
return app;
}
A few notes:
- Helmet sets sensible security headers.
- CORS should list specific origins, never
*combined with credentials. CORS is a browser mechanism, not access control; it doesn't stop scripts or servers calling your API. - Rate limiting with
express-rate-limituses in-memory counters by default, which only work for a single process. When you run multiple instances, use a shared store (Redis is common). Apply stricter limits to login, signup, and password-reset routes. trust proxymust match your infrastructure. Set it wrong and either every request looks like it comes from your proxy, or clients can spoof their IP with headers.
Structured Logging With Pino
Pino produces fast, structured JSON logs that aggregators can search. pino-http attaches a logger to each request (req.log) and records method, URL, status, and duration. Log JSON in production (use pino-pretty only locally), redact credentials and tokens, and include a request ID so you can trace a request across services.
Environment Configuration
Read configuration from environment variables, validate it once at startup, and fail fast if anything is missing:
// src/config.js
import { z } from "zod";
const schema = z.object({
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.string().min(1),
JWT_SECRET: z.string().min(32),
CORS_ORIGINS: z
.string()
.default("http://localhost:5173")
.transform((s) => s.split(",").map((o) => o.trim())),
});
const result = schema.safeParse(process.env);
if (!result.success) {
console.error("Invalid environment configuration:", result.error.issues);
process.exit(1);
}
export const config = result.data;
Keep .env out of version control, commit an .env.example with placeholder values, and store production secrets in your hosting platform's secret manager.
Documenting With OpenAPI
An OpenAPI document describes every endpoint and response, and powers interactive docs and client generation. Two approaches:
- Design-first: write
openapi.yamlby hand, review it with front-end and mobile developers, then implement it. - Code-first: generate the spec from your validation schemas so docs can't drift from behavior. Zod 4 includes
z.toJSONSchema(), and libraries such as@asteasolutions/zod-to-openapibuild full OpenAPI documents from Zod schemas.
Serve the docs with Swagger UI or Scalar.
Testing With Supertest and node:test
Because createApp() doesn't open a port, Supertest can exercise the full middleware stack in-process. Node's built-in test runner keeps dependencies minimal (Vitest works the same way if you prefer it):
// test/projects.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
import request from "supertest";
import { createApp } from "../src/app.js";
const app = createApp();
test("GET /healthz returns ok", async () => {
const res = await request(app).get("/healthz");
assert.equal(res.status, 200);
assert.deepEqual(res.body, { status: "ok" });
});
test("rejects requests without a token", async () => {
const res = await request(app).get("/v1/projects");
assert.equal(res.status, 401);
assert.equal(res.body.error.code, "unauthorized");
});
test("validates the create payload", async () => {
const res = await request(app)
.post("/v1/projects")
.set("Authorization", "Bearer " + (await makeTestToken()))
.send({ name: "" });
assert.equal(res.status, 400);
assert.equal(res.body.error.code, "validation_failed");
});
Here makeTestToken() is a small helper that signs a token with your test secret. Prefer a real test database (a Docker container works well) over heavy mocking, and run tests in CI on every pull request.
Deployment
Use a supported Node.js LTS
Run production on an LTS release line that's still in support. Node.js 20 reached end of life in April 2026, so move to Node 22 or 24 (or a newer LTS) if you haven't already. Check the release schedule on nodejs.org before you pick.
Process managers and containers
On a VPS, a process manager such as PM2 or a systemd service restarts the app if it crashes and on reboot. On container platforms, the container runtime does that job:
FROM node:24-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY src ./src
USER node
EXPOSE 3000
CMD ["node", "src/server.js"]
Run node directly rather than through npm start so termination signals reach your process.
Health checks and graceful shutdown
Expose a liveness endpoint (/healthz, which says the process is up) and, if your platform supports it, a readiness endpoint that also checks the database. When the platform stops an instance, it sends SIGTERM; finish in-flight requests before exiting:
// src/server.js
import { createApp } from "./app.js";
import { config } from "./config.js";
import { db } from "./db.js";
const app = createApp();
const server = app.listen(config.PORT, () => {
console.log("API listening on port " + config.PORT);
});
function shutdown(signal) {
console.log(signal + " received, shutting down");
server.close(async () => {
await db.end();
process.exit(0);
});
// Force exit if connections don't close in time
setTimeout(() => process.exit(1), 10_000).unref();
}
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));
Next Steps
Express rewards a small, disciplined setup: clear structure, strict validation, consistent errors, and the security basics in place from the first commit. Start with the skeleton above and add complexity only when your product needs it. If your API is the backbone of a SaaS product, our SaaS development page outlines how we approach multi-tenant platforms.
Planning a new API or modernizing an existing Node.js backend? Take a look at our React and Node.js development services, or request a quote and tell us what you're building.
DLN Web Studio
Author


