Skip to main content

How to Use Middleware in Node.js (Express)

How to Use Middleware in Node.js (Express) with Real-Time Example

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 object
  • res – the HTTP response object
  • next() – 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 auth
  • GET /dashboard – requires Authorization: Bearer secrettoken123 header

๐Ÿ” 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

Popular posts from this blog

How to Use L5-Swagger for API Documentation in Laravel

Integrating Swagger in Laravel: Annotations, JSON, and YAML What is Swagger? Swagger (OpenAPI) is a powerful tool for generating interactive API documentation. It helps developers understand and test your API easily. ✅ Step-by-Step Guide to Setup L5-Swagger 1. Install L5-Swagger Package composer require "darkaonline/l5-swagger" 2. Publish Config & View Files This command publishes the config file to config/l5-swagger.php : php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" 3. Configure Swagger (Optional) Edit the file config/l5-swagger.php to update: API Title Base Path Directories to scan for annotations 4. Add Swagger Annotations Add these before your controller class: /** * @OA\Info( * version="1.0.0", * title="Your API Title", * description=...

How to Send Emails in Node.js using Nodemailer and Ethereal

How to Send Email in Node.js using Nodemailer Email functionality is essential in modern web applications. Whether you're sending confirmation emails, password resets, or notifications, Node.js with Nodemailer makes this simple. In this blog, we'll walk through setting up email sending using Node.js , Express , and Ethereal Email for testing. ๐Ÿงพ Prerequisites Node.js installed Basic knowledge of Express.js Internet connection ๐Ÿ“ Project Structure project-folder/ ├── index.js ├── .env ├── package.json └── app/ └── controller/ └── emailSendController.js ๐Ÿ“ฆ Step 1: Install Dependencies npm init -y npm install express nodemailer dotenv npm install --save-dev nodemon ๐Ÿ” Configure nodemon (Optional but Recommended) Update your package.json with a custom start script: "scripts": { "start": "nodemon index.js" } ๐Ÿ” Step 2: Create a .env File Create a .env file a...

Realtime Device Tracker using Node.js, Socket.IO & Leaflet

Realtime Device Tracker using Node.js, Socket.IO & Leaflet In this tutorial, you’ll learn how to build a realtime location tracking application that uses the browser’s GPS, Socket.IO for live communication, and Leaflet.js to display users on a map. ๐Ÿš€ Project Overview Backend: Node.js, Express.js, Socket.IO Frontend: HTML, Leaflet.js, Socket.IO client Features: Live GPS tracking, multi-user map, disconnect cleanup ๐Ÿ“ Folder Structure project-root/ ├── app.js ├── package.json ├── src/ │ ├── public/ │ │ ├── css/ │ │ │ └── style.css │ │ └── js/ │ │ └── script.js │ ├── routes/ │ │ └── routers.js │ ├── socket/ │ │ └── socketHandler.js │ └── views/ │ └── index.ejs ๐Ÿง  How It Works Each user shares their location using the browser's navigator.geolocation API. Location is sent to the server via Socket.IO . The server broadcasts each user’s position to all clien...