DEV Community

rashidpbi
rashidpbi

Posted on

Understanding Middleware in Express.js (With Simple Implementation)

If you've worked with Express.js, you've probably seen app.use() everywhere. But what exactly is middleware? How does app.use(fn) work behind the scenes?

In this post, let's break down what middleware is and how it works in Express.js

🔑 What is Middleware?

In Express.js, middleware is simply a function that runs during the request-response cycle. It has access to the request object (req), the response object (res), and a special next() function that passes control to the next middleware.

Express uses middleware to handle logging, authentication, error handling, CORS, body parsing, and more.

🏗 The Syntax of Middleware

Middleware is typically added using app.use():

app.use((req, res, next) => {
  console.log('Middleware executed!');
  next(); // Pass control to the next middleware
});
Enter fullscreen mode Exit fullscreen mode

If you don't call next(), the request will hang and never reach the final route handler.

🌐 Common Use Cases of Middleware

Here are a few examples of middleware in action:

1️⃣ Logging Every Request

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url} at ${new Date().toISOString()}`);
  next();
});
Enter fullscreen mode Exit fullscreen mode

✅ This runs for every request and logs request info.

2️⃣ Applying Middleware to Specific Routes

app.use('/admin', (req, res, next) => {
  console.log('Admin route accessed');
  next();
});
Enter fullscreen mode Exit fullscreen mode

✅ Runs only for /admin and its sub-routes.

3️⃣ Using Third-Party Middleware (e.g., CORS)

const cors = require('cors');
app.use(cors());
Enter fullscreen mode Exit fullscreen mode

✅ Enables CORS for all requests.

4️⃣ Serving Static Files

app.use(express.static('public'));
Enter fullscreen mode Exit fullscreen mode

✅ Serves HTML, CSS, JS, and images directly from the public folder.

🚨 Error-Handling Middleware

In Express, error-handling middleware looks slightly different—it has 4 parameters:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});
Enter fullscreen mode Exit fullscreen mode

Express automatically detects this pattern and uses it to catch errors.

🎯 Key Takeaways

✅ Middleware is at the heart of Express.js.

✅ It allows preprocessing of requests before they hit route handlers.

app.use(fn) registers middleware functions in a chain-like system.

✅ Calling next() is crucial to move to the next middleware.

Top comments (0)