Middleware is one of the most powerful concepts in Express.js, allowing you to intercept and modify requests and responses. In this guide, we’ll explore middleware usage in Express — with a real-world use case: Authentication Middleware.
๐ What is Middleware?
In Express.js, middleware is a function that sits between the request and response in the HTTP lifecycle. It has access to:
req– the HTTP request objectres– the HTTP response objectnext()– a function that passes control to the next middleware
Think of middleware as the logic that can:
- Log request details
 - Check if a user is authenticated
 - Parse request bodies (JSON, form data, etc.)
 - Serve static files
 - Handle errors
 
Middleware runs before the final route handler and can either:
- Terminate the request (by sending a response)
 - Call 
next()to pass control to the next middleware or route 
// Structure of a middleware
function myMiddleware(req, res, next) {
  // Do something with the request or response
  next(); // Call next to move to the next step
}
  In Express, you can apply middleware:
- Globally using 
app.use() - On specific routes like 
app.get('/route', middleware, handler) 
Example use cases:
- Authenticate users (as shown in this guide)
 - Log incoming requests
 - Catch and handle errors in one place
 
๐ Real-Time Example: Auth Middleware
Let's build a middleware that simulates token authentication and applies it to protected routes like /dashboard.
const express = require('express');
const app = express();
// Sample auth middleware
const authMiddleware = (req, res, next) => {
  const token = req.headers['authorization'];
  if (token === 'Bearer secrettoken123') {
    next(); // allow request to proceed
  } else {
    res.status(401).json({ message: 'Unauthorized access' });
  }
};
// Public route
app.get('/', (req, res) => {
  res.send('Public Home Page');
});
// Protected route
app.get('/dashboard', authMiddleware, (req, res) => {
  res.send('Welcome to your dashboard!');
});
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});
  ๐ง  What is Bearer secrettoken123?
  The string Bearer secrettoken123 simulates a token-based authentication system.
- Bearer is a keyword indicating token-based authorization (commonly used with JWTs).
 - secrettoken123 is a dummy token used to demonstrate how the middleware checks credentials.
 
In a real app, this token would be a unique JWT sent by the client after login and verified on the server for identity.
๐งช Try It Out
Now try accessing:
GET /– accessible without authGET /dashboard– requiresAuthorization: Bearer secrettoken123header
๐ Middleware Use Cases
- Authentication & Authorization
 - Request logging (e.g., using 
morgan) - Body parsing with 
express.json() - Rate limiting (e.g., to prevent abuse)
 - Error handling
 
๐ Chaining Multiple Middlewares
You can stack middlewares like this:
app.get('/profile', loggerMiddleware, authMiddleware, (req, res) => {
  res.send('User Profile');
});
  ๐ Final Thoughts
Middleware in Express.js gives you fine-grained control over request/response handling. Mastering it will level up your backend development skills significantly — especially when building secure, production-ready APIs.
Pro Tip: Try combining custom and third-party middleware for scalable architecture.
Happy coding! ๐ก️๐ง
Comments
Post a Comment