DevAcademy
LearnNode.jsMiddleware
IntermediateNode.js

Middleware

Functions that run between a request arriving and a response being sent — the core of Express's design.

Reading Time

14 min

Lesson

Lesson 20 of 34

What Middleware Is

Middleware is a function with access to the request, the response, and a next() function to pass control to the next middleware in the chain. Logging, authentication, parsing a request body, and error handling are all implemented as middleware in Express.

A Simple Logging Middleware

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Middleware Runs in Order

app.use() and route handlers form a chain, executed top to bottom in the order they are registered. Each middleware must call next() to continue to the next one — forgetting to call next() (or send a response) leaves the request hanging forever.

Middleware for a Specific Route Only

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Common Built-in and Third-Party Middleware

MiddlewarePurpose
express.json()Parses a JSON request body
express.static(dir)Serves static files from a folder
cors()Handles Cross-Origin Resource Sharing headers
helmet()Sets security-related HTTP headers
morgan()HTTP request logging

A Middleware That Never Calls next() Hangs the Request

If a middleware neither calls next() nor sends a response (res.send(), res.json(), res.end()), the request never completes — it just hangs until the client eventually times out.

Best Practice

Order matters — register broadly-applicable middleware (logging, CORS, body parsing) before your routes, and route-specific middleware (like auth checks) directly on the routes that need it.

Interview Questions

Quick Quiz

1. What must a middleware function call to pass control onward?

2. What happens if a middleware neither calls next() nor sends a response?

3. What does the express.json() middleware do?