Node.js HTTP, Express and REST APIs
Most Node.js code in production serves HTTP. This page goes from the built-in node:http module to an Express 5 API with routers, middleware, validation, authentication and a central error handler, and ends with the REST design rules that keep an API predictable. Everything uses one example: the orders API behind OrdersPortal.
Samples were run with Node.js 22.23 as ES modules (.mjs). The Express sample uses express@5.3.0 and zod@4.6.7 (npm install express zod); the authentication fragment uses jsonwebtoken@9.0.3. Each complete sample starts a server on a free port, calls itself with the built-in fetch, prints the results and exits.
Topics on this page
Section titled “Topics on this page”| Topic | Use it to |
|---|---|
| Native HTTP module | Understand what every framework is built on. |
| Express routing | Organize endpoints with routers and route parameters. |
| Middleware | Add logging, parsing, authentication and other cross-cutting steps. |
| Error handling | Turn failures into consistent responses without leaking details. |
| REST API design | Choose methods, status codes, validation and response shapes. |
Native HTTP module
Section titled “Native HTTP module”node:http gives you a server and a callback that receives every request (req, a readable stream with the method, URL and headers) and a response (res, a writable stream). You set the status and headers, write the body and call res.end(). There is no routing, no body parsing and no error handling: you parse req.url yourself, usually with the WHATWG URL class. That is fine for a health endpoint, a tiny internal tool or a proxy, and it is worth knowing because Express’s req and res are these same objects with extra methods.
import { createServer } from 'node:http';
const orders = new Map([[1001, { id: 1001, status: 'shipped', total: 61.98 }]]);
const server = createServer((req, res) => { const url = new URL(req.url, `http://${req.headers.host}`); const match = url.pathname.match(/^\/orders\/(\d+)$/);
if (req.method === 'GET' && match) { const order = orders.get(Number(match[1])); res.writeHead(order ? 200 : 404, { 'content-type': 'application/json' }); res.end(JSON.stringify(order ?? { error: 'Order not found' })); return; } res.writeHead(404, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'Route not found' }));});
server.listen(0, async () => { const base = `http://localhost:${server.address().port}`; for (const path of ['/orders/1001', '/orders/9999', '/customers']) { const response = await fetch(base + path); console.log(`GET ${path} -> ${response.status} ${await response.text()}`); } server.close();});Output:
GET /orders/1001 -> 200 {"id":1001,"status":"shipped","total":61.98}GET /orders/9999 -> 404 {"error":"Order not found"}GET /customers -> 404 {"error":"Route not found"}Pitfalls:
- Forgetting
res.end()leaves the client waiting until it times out. - Reading the body without a limit. Collecting
reqchunks with no size cap lets one client exhaust memory. - Throwing inside the callback crashes the process unless you catch it; frameworks add that safety net.
Express routing
Section titled “Express routing”Express is a thin framework on top of node:http. Express 5 (5.0 shipped in September 2024; 5.3 is current) is the version to use for new work: it requires Node.js 18 or later, forwards rejected promises from async handlers to the error handler, and uses a stricter path syntax (wildcards must be named, such as /files/*path). An app is a list of routes and middleware matched in registration order. express.Router() groups related routes into a module that you mount on a prefix, which keeps each resource in its own file.
Route parameters (/:id) arrive as strings in req.params; query strings in req.query; the parsed JSON body in req.body once express.json() has run (in Express 5 req.body is undefined when no parser ran). res.json() sets the content type and serializes, res.status() sets the code, and res.location() sets the Location header for a created resource.
This complete program is the OrdersPortal API used in the rest of the page:
import express from 'express';import { z } from 'zod';
// --- data access (an in-memory stand-in for a database) ---const orders = new Map([[1001, { id: 1001, customerEmail: 'ada@example.test', items: 2, status: 'open' }]]);let nextId = 1002;const findOrder = async (id) => orders.get(id);
// --- middleware ---function requestLogger(req, res, next) { const started = performance.now(); res.on('finish', () => { console.log(` log: ${req.method} ${req.originalUrl} ${res.statusCode} ${(performance.now() - started).toFixed(0)}ms`); }); next();}
function requireApiKey(req, res, next) { if (req.get('x-api-key') !== 'test-key') { return res.status(401).json({ error: 'Missing or invalid API key' }); } next();}
const validateBody = (schema) => (req, res, next) => { const result = schema.safeParse(req.body); if (!result.success) return res.status(400).json({ errors: z.flattenError(result.error).fieldErrors }); req.body = result.data; next();};
// --- routes ---const CreateOrder = z.object({ customerEmail: z.email(), items: z.number().int().min(1).max(100),});
const ordersRouter = express.Router();
ordersRouter.get('/:id', async (req, res) => { const order = await findOrder(Number(req.params.id)); if (!order) return res.status(404).json({ error: 'Order not found' }); res.json(order);});
ordersRouter.post('/', requireApiKey, validateBody(CreateOrder), (req, res) => { const order = { id: nextId++, ...req.body, status: 'open' }; orders.set(order.id, order); res.status(201).location(`/api/orders/${order.id}`).json(order);});
ordersRouter.post('/:id/cancel', requireApiKey, async (req, res) => { // Express 5 forwards this rejected promise to the error handler; no try/catch needed. throw new Error(`Payment provider timeout while cancelling ${req.params.id}`);});
// --- app ---const app = express();app.use(requestLogger);app.use(express.json({ limit: '100kb' }));app.use('/api/orders', ordersRouter);app.use((req, res) => res.status(404).json({ error: 'Route not found' }));app.use((err, req, res, next) => { // four parameters marks the error handler console.error(` error: ${err.message}`); res.status(err.status ?? 500).json({ error: err.expose ? err.message : 'Internal server error' });});
const server = app.listen(0, async () => { const base = `http://localhost:${server.address().port}/api/orders`; const json = { 'content-type': 'application/json', 'x-api-key': 'test-key' }; const calls = [ ['GET', '/1001'], ['POST', '/', { customerEmail: 'ben@example.test', items: 3 }], ['POST', '/', { customerEmail: 'not-an-email', items: 0 }], ['POST', '/1001/cancel', {}], ['GET', '/9999'], ]; for (const [method, path, body] of calls) { const res = await fetch(base + path, { method, headers: json, body: body && JSON.stringify(body) }); console.log(`${method} ${path} -> ${res.status} ${await res.text()}`); } server.close();});Output (durations vary):
log: GET /api/orders/1001 200 2msGET /1001 -> 200 {"id":1001,"customerEmail":"ada@example.test","items":2,"status":"open"} log: POST /api/orders/ 201 1msPOST / -> 201 {"id":1002,"customerEmail":"ben@example.test","items":3,"status":"open"} log: POST /api/orders/ 400 1msPOST / -> 400 {"errors":{"customerEmail":["Invalid email address"],"items":["Too small: expected number to be >=1"]}} error: Payment provider timeout while cancelling 1001 log: POST /api/orders/1001/cancel 500 1msPOST /1001/cancel -> 500 {"error":"Internal server error"} log: GET /api/orders/9999 404 0msGET /9999 -> 404 {"error":"Order not found"}Pitfalls:
- Route order matters.
/:idregistered before/summarycapturessummaryas an ID; register specific paths first. - Parameters are strings. Convert and validate
req.params.idbefore using it as a number. - Upgrading from Express 4. Unnamed wildcards (
*) and regex-like path characters now throw at startup; rename them as the Express 5 migration guide describes.
Middleware
Section titled “Middleware”Middleware is a function (req, res, next) that runs before the route handler. It can read or change the request, end the response itself (for example with a 401), or call next() to pass control on. app.use(fn) applies it to every request, app.use('/api', fn) to a path prefix, and router.post('/', fnA, fnB, handler) to one route, as requireApiKey and validateBody do above. Everything runs in registration order, so the usual stack is: security headers and CORS, request logging, body parsing, rate limiting, authentication, routes, a 404 handler and finally the error handler.
Well-maintained packages cover the common needs: helmet sets security headers, cors answers cross-origin preflight requests for an allow-list of origins, express-rate-limit throttles by client, and pino-http or morgan log requests. For authentication with bearer tokens, verify the signature and the claims you rely on, then attach the user to req:
// Fragment: JWT authentication middleware (jsonwebtoken 9); verified separately, not part of the program above.import jwt from 'jsonwebtoken';
export function requireUser(req, res, next) { const header = req.get('authorization') ?? ''; if (!header.startsWith('Bearer ')) return res.status(401).json({ error: 'Authentication required' }); try { const payload = jwt.verify(header.slice(7), process.env.JWT_SECRET, { algorithms: ['HS256'], // never let the token pick the algorithm audience: 'orders-api', issuer: 'https://login.example.test/', }); req.user = { id: payload.sub, roles: payload.roles ?? [] }; next(); } catch { res.status(401).json({ error: 'Invalid or expired token' }); }}Use 401 when the caller is not authenticated and 403 when an authenticated caller lacks permission for this order.
Pitfalls:
- Neither calling
next()nor responding hangs the request. - Calling
next()after sending a response triggers “Cannot set headers after they are sent”. cors()with no options allows every origin; pass an explicitoriginlist in production.
Error handling
Section titled “Error handling”Express recognizes error-handling middleware by its four parameters (err, req, res, next); register it last. Any next(err) call, any synchronous throw in a handler and, from Express 5, any rejected promise returned by an async handler or middleware all end up there. In Express 4 you needed a wrapper such as asyncHandler or try/catch with next(err) for every async route; in Express 5 that boilerplate can go.
A good error handler logs the full error with request context, maps known error types to status codes (validation to 400, not found to 404, conflict to 409) and returns a generic message for anything unexpected. The sample checks err.expose, a convention from the http-errors package that Express uses for errors that are safe to show to clients, such as a 400 from a malformed JSON body. The 404 handler before it catches requests that matched no route.
Pitfalls:
- Returning
err.messageor stack traces for 500s leaks internals such as SQL or file paths. - Error handler with three parameters is treated as normal middleware and never receives errors.
- Swallowing errors in a
catchwithout responding leaves the request hanging; rethrow or callnext(err).
REST API design
Section titled “REST API design”REST maps operations onto resources and HTTP methods: GET /api/orders/1001 reads, POST /api/orders creates, PUT replaces, PATCH updates part of a resource, DELETE removes. Use plural nouns for collections, nest only for real ownership (/api/orders/1001/lines), and model actions that are not plain updates as sub-resources (POST /api/orders/1001/cancel). GET, PUT and DELETE must be safe to retry; for POST that charges money, accept an idempotency key.
Validate every body, parameter and query string at the edge with a schema, as validateBody(CreateOrder) does with Zod 4, and replace req.body with the parsed result so handlers only see clean data. Status codes that matter most:
| Status | Meaning |
|---|---|
| 200 OK | Successful read or update with a body |
| 201 Created | Resource created; send a Location header |
| 204 No Content | Success with no body, such as a delete |
| 400 Bad Request | Validation failed or malformed input |
| 401 Unauthorized | Not authenticated |
| 403 Forbidden | Authenticated but not allowed |
| 404 Not Found | No such resource |
| 409 Conflict | State conflict, such as cancelling a shipped order |
| 422 Unprocessable Content | Well-formed but semantically invalid (some teams use 400 for all validation errors; pick one) |
| 429 Too Many Requests | Rate limit hit |
| 500 Internal Server Error | Unexpected failure |
Paginate collections (?page=2&limit=50, capping limit, or cursor-based ?after=1050 for large tables) and return the paging data with the results. Version breaking changes in the path (/api/v2/orders) or a header, and document the API with OpenAPI.
Pitfalls:
- Verbs in URLs (
/getOrders,/createOrder) duplicate what the method already says. - 200 with an error body breaks clients, caches and monitoring that rely on status codes.
- Unbounded list endpoints turn one request into a full-table scan as data grows.
Choosing between them
Section titled “Choosing between them”| Need | Choose |
|---|---|
| A health check, webhook receiver or proxy with one or two routes | node:http |
| A typical JSON API or server-rendered site | Express 5 |
| Strong schema-first validation and serialization performance | Fastify is a popular alternative; the concepts on this page carry over |
| Full-stack React with server rendering | A meta-framework (React Router framework mode, Next.js) |
Interview questions
Section titled “Interview questions”What does next() do, and what happens if you pass it an argument?
next() hands control to the next matching middleware or route. next(err) with any value other than 'route' or 'router' skips the remaining normal middleware and goes to the error handlers.
How did async error handling change in Express 5?
Express 5 attaches a rejection handler to the promise returned by a handler or middleware and calls next(err) for you. In Express 4 an unhandled rejection in an async route never reached the error handler, so you needed wrappers or try/catch.
Where do you validate input, and why replace req.body?
At the edge, before the handler, with a schema. Replacing req.body with the parsed output removes unknown fields and applies coercions, so the handler cannot accidentally use unvalidated data such as an extra status: "paid" property.
Why 401 versus 403? 401 means the request has no valid credentials, so the client should authenticate. 403 means the identity is known but not permitted for this resource, so retrying with the same credentials will not help.
Senior scenario: the orders API intermittently returns 502 from the load balancer during deploys. What do you check?
Graceful shutdown first: on SIGTERM the process should stop accepting connections (server.close()), let in-flight requests finish, close database pools and then exit, and the readiness probe should fail before shutdown starts. Then check keep-alive timeouts: Node’s server.keepAliveTimeout must be longer than the load balancer’s idle timeout, otherwise Node closes sockets the balancer still reuses. Finally confirm that crashes from unhandled errors are not the cause by checking the error handler and process logs.
Related pages
Section titled “Related pages”- Node.js runtime: event loop, modules, npm and config covers configuration and the event loop these servers depend on.
- Files and streams for streaming request and response bodies.
- Node.js interview questions
- Node.js overview