BackendExpressNode.jsBackendAPISecurity

Express Middleware Deep Dive: Build Custom Auth, Logging, and Validation Layers

Express middleware is the backbone of every Node.js API. Understanding how to build and compose custom middleware transforms your architecture.

Abdur Razzak

Abdur Razzak

Full-Stack Web Developer

January 8, 2026 9 min read

Express middleware functions are the building blocks of every Express application. A middleware function is simply a function that receives the request object, the response object, and a next function, performs some operation, and then either terminates the request-response cycle by sending a response or passes control to the next middleware by calling next. The power of middleware comes from composability: you can stack many middleware functions on top of each other and each one handles a specific, focused concern. Authentication middleware checks whether the request carries valid credentials. Logging middleware records request details before any route handler processes the request. Validation middleware examines the request body and rejects malformed input before it reaches business logic. Rate limiting middleware counts requests per client and blocks excessive ones. Each concern is isolated in its own function, making the application easy to test, modify, and extend.

How Middleware Works: The Request Pipeline

Express processes an incoming request by passing it through a pipeline of middleware functions in the order they were registered with app.use or router.use. Each middleware function runs in sequence, and each one must either send a response to terminate the cycle or call next to pass control to the next function in the pipeline. If next is never called and no response is sent, the request hangs until the client timeout is reached. Calling next with an argument, such as next(new Error('something failed')), skips all remaining regular middleware and jumps directly to the error-handling middleware. This is the standard pattern for routing errors from middleware functions to the centralized error handler. Middleware registered with app.use applies to all routes. Middleware passed as an argument to a route handler applies only to that route and runs before the route handler function.

Building an Authentication Middleware

An authentication middleware reads a JWT from the Authorization header, verifies its signature against your secret key, decodes the payload, and attaches the user information to the request object for downstream handlers to use. If the header is missing, call next with a 401 unauthorized error. If the token is expired, malformed, or signed with an incorrect secret, call next with a 401 error. If verification succeeds, set req.user to the decoded payload and call next without arguments to allow the request to proceed to the route handler. Route handlers can then access req.user to retrieve the authenticated user's ID, roles, and permissions. Apply this middleware selectively to protected routes by passing it as an argument to specific route handlers, or apply it globally with app.use and selectively skip it for public routes by checking a list of public route patterns.

Building a Request Logging Middleware

A custom request logging middleware captures structured information about every incoming request and outgoing response. On every request, record the HTTP method, URL, IP address, and start timestamp. Because response details like status code and response time are only available after the route handler completes, hook into the response finish event to log the completion details. Attach a listener to the res.on('finish', callback) event, which fires after the response has been sent. Inside the callback, calculate the elapsed time by comparing the current timestamp to the start timestamp stored when the request arrived. Structure the log output as a JSON object with consistent field names so that log aggregation services like Datadog, Splunk, or the ELK stack can parse and index each field independently. Include a unique request ID generated at the start of each request to correlate all log entries from a single request across distributed systems.

Input Validation Middleware with Zod

A validation middleware factory accepts a Zod schema as its configuration and returns a middleware function that validates the request body against that schema before the route handler runs. Create a validate function that takes a Zod schema and returns an Express middleware. Inside the middleware, call schema.safeParse(req.body), which returns either a success result containing the parsed data or a failure result containing the validation errors. On failure, respond with HTTP 400 and a structured error body that includes the specific field errors from the Zod result. On success, replace req.body with the parsed result data, which includes type coercions and transformations defined in the schema. Apply the validator middleware to specific routes by passing it as an argument before the route handler. This pattern keeps route handlers completely free of validation logic and makes the validation contract for each endpoint explicit and machine-readable.

Composing Middleware: Order and Scope

Middleware ordering in Express is critically important because functions execute in the order they are registered. Global middleware registered with app.use runs before any route handlers, regardless of where the route handlers are defined. Error-handling middleware with four parameters must be registered after all other middleware and route handlers, because it only receives control when next is called with an error argument. Router-level middleware registered on an Express Router instance applies only to the routes defined on that router, not the entire application. This scoping capability is the foundation for building modular Express applications where each feature area has its own router with its own middleware stack. For example, the admin router applies strict authentication and authorization middleware, while the public API router applies only rate limiting and request logging.

Testing Middleware in Isolation

Well-designed Express middleware functions are pure enough to be tested in isolation without running the full Express server. Create mock request and response objects that implement the properties and methods your middleware uses. A mock request object needs the properties your middleware reads, such as headers.authorization for auth middleware. A mock response object needs the methods your middleware calls, such as status, json, and send, mocked as Jest spy functions that record the calls made to them. A mock next function records whether it was called and with what argument. Pass these mocks to your middleware function directly and assert on the mock spy call records. Integration tests using Supertest can test the full request pipeline including middleware composition, but isolated unit tests for individual middleware functions are faster and provide more targeted feedback when a specific middleware function has a bug.

Share this article

All posts
#Express#Node.js#Backend#API#Security
Abdur Razzak — Full Stack Web Developer
⭐ Top Rated

Upwork Top Rated Developer

Work With a Developer Clients Trust