#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Express - Advanced Topics

Middleware

In Express, middleware is a function that runs between the moment a request arrives and the moment a response is sent. Each middleware receives the request object, the response object and a next function. It can read or change the request, end the response itself, or call next() to hand control to the next function in line. Parsing JSON bodies, logging, checking authentication, serving static files and handling errors are all done with middleware.

The request pipeline

Think of an Express app as a list of functions checked in the order you register them. When a request comes in, Express walks down the list. Every middleware or route whose path matches gets a turn. Route handlers such as app.get('/users', ...) are really just middleware that usually end the response instead of calling next().

const express = require('express');
const app = express();

// Built-in middleware: parse JSON request bodies into req.body
app.use(express.json());

// Simple logger that runs for every request
app.use((req, res, next) => {
  const started = Date.now();
  res.on('finish', () => {
    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - started}ms`);
  });
  next();
});

// Serve files from the public folder
app.use(express.static('public'));

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' });
});

app.listen(process.env.PORT || 3000);

Kinds of middleware

  • Application-level: registered with app.use() or app.METHOD().
  • Router-level: registered on an express.Router() so it applies only to that group of routes.
  • Built-in: express.json(), express.urlencoded() and express.static().
  • Third-party: packages such as cors, helmet and morgan.
  • Error-handling: functions with four parameters, (err, req, res, next).

Scoping middleware to some routes

Middleware does not have to run everywhere. Pass a path to app.use('/admin', fn) to limit it to URLs starting with /admin, or put it directly in a route definition. Several functions can be listed, and they run left to right.

function requireJson(req, res, next) {
  if (!req.is('application/json')) {
    return res.status(415).json({ error: 'Send JSON' });
  }
  next();
}

app.post('/api/products', requireJson, (req, res) => {
  res.status(201).json({ created: req.body.name });
});

// Error handler goes last
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: 'Something went wrong' });
});

Mistakes that make requests hang

If a middleware neither sends a response nor calls next(), the request simply hangs until the client times out. This is the bug beginners hit most often. Every path through a middleware must end in one of the two.

The opposite error is doing both: sending a response and then calling next(), or calling res.send() twice. Express then throws "Cannot set headers after they are sent to the client". Using return res.status(...) when you end early prevents the code below from running.

Order is the other big source of bugs. If express.json() is registered after your routes, req.body is undefined inside them. If the error handler is registered before the routes, it never sees their errors. Register parsers and loggers first, routes next, and error handlers last.

In Express 4, an error thrown inside an async handler is not caught automatically. Wrap the body in try...catch and call next(err), so the error handler receives it.

When a request seems to skip your middleware, log inside it first. Often the path given to app.use does not match because of a missing leading slash, or a router was mounted at a different prefix than you assumed. req.originalUrl shows the full path, while req.path is relative to where the router is mounted.

What to remember

Middleware is a chain of (req, res, next) functions run in registration order. Each one must either respond or call next(). Put body parsers first, error handlers last, and scope middleware to paths or routers when it is not needed everywhere.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course