Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to Node.js
Node.js Middleware Complete Guide

Node.js Middleware Complete Guide

Node.js308 viewsBy Admin
nodejsmiddleware

What is Middleware?

Middleware are functions that run between receiving a request and sending a response. Each has access to req, res, and next. They power logging, auth, parsing, and error handling in Express.

The Middleware Signature

function middleware(req, res, next) {
  // do something
  next(); // pass control to the next middleware
}
app.use(middleware);

Example: Request Logger

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
  next();
});

Example: Authentication Guard

function requireAuth(req, res, next) {
  const token = req.headers.authorization;
  if (!token) return res.status(401).json({ error: "Unauthorized" });
  req.user = verifyToken(token);
  next();
}

app.get("/profile", requireAuth, (req, res) => {
  res.json(req.user);
});

Built-in & Popular Middleware

MiddlewarePurpose
express.json()Parse JSON bodies
corsEnable cross-origin requests
helmetSecurity headers
morganHTTP request logging

Error-Handling Middleware (4 args)

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: "Something broke" });
});

FAQs

Does middleware order matter?

Yes — middleware runs top to bottom. Put logging and body parsing early, error handlers last.

What if I forget next()?

The request hangs forever. Always call next() (or send a response). More in our Node.js guides.