MyInternships.in

Express.js & REST APIs

Node.js Express Middleware

Middleware is a function receiving (req, res, next) that runs before the route handler. It can inspect and modify the request, end the response early, or call next() to continue the chain.


What is Express Middleware in Node.js?

Middleware is a function receiving (req, res, next) that runs before the route handler. It can inspect and modify the request, end the response early, or call next() to continue the chain.

Why Express Middleware matters

Authentication, logging, rate limiting, CORS and body parsing are all middleware. Understanding the chain is the core of understanding Express.

Express Middleware example

Writing and applying middleware
JavaScript
function requestLogger(req, res, next) {
  const start = Date.now();
  res.on('finish', () => {
    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - start}ms`);
  });
  next();
}

function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Not authenticated' });
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid token' });
  }
}

app.use(requestLogger);                        // every request
app.get('/api/me', requireAuth, getProfile);   // one route

Key points to remember

  • Order matters — middleware runs top to bottom as registered.
  • Either call next() or send a response; doing neither hangs the request.
  • Attach derived data to req (such as req.user) for later handlers.
  • Error middleware has four parameters and must be registered last.

Common mistakes with Express Middleware

  • Forgetting next(), which leaves the client waiting until it times out.
  • Calling next() after already sending a response.
  • Registering error-handling middleware before the routes.

Node.js Express Middleware— Interview Questions & FAQs

What happens if middleware does not call next()?+

The request stops there. If the middleware also sent no response, the client waits until it times out — which is exactly what a hanging Express endpoint usually means.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships