Q: How to create a custom middleware?

Understanding Middleware

Middleware is a function that has access to the request (req), response (res), and the next middleware function in the application's request-response cycle. It can execute code, make changes to the request and response objects, end the request-response cycle, and call the next middleware function to continue processing.

Why Use Middleware?

  1. Code Reusability: Middleware can be used across different routes, allowing you to maintain cleaner and more manageable code.
  2. Separation of Concerns: By processing requests through middleware, you can separate specific functionalities, making your codebase well-organized.
  3. Functionality Enhancement: Middleware allows you to introduce additional features like logging, authentication, error handling, and more without cluttering your route handlers.

Creating a Custom Middleware

Let's walk through creating a simple logging middleware that will log the details of each incoming request.

Step 1: Setting Up Your Project

  1. Initialize Your Project: If you haven’t already, create a new directory for your project and initialize Node.js:

    mkdir express-middleware-example cd express-middleware-example npm init -y
  2. Install Express: Install Express.js via npm:

    npm install express
  3. Create Your Server File: Create a file named server.js:

    touch server.js

Step 2: Write the Custom Middleware

In your server.js file, start by importing Express and then set up your basic server:

const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000;

Now, let's create our custom logging middleware:

const loggerMiddleware = (req, res, next) => { console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`); next(); // Pass control to the next middleware or route handler };

Step 3: Use the Middleware in Your Application

To use the middleware we've just created, add it to your Express application like so:

app.use(loggerMiddleware); // Register the middleware app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });

Step 4: Test Your Middleware

Now that everything is set up, you can run your server:

node server.js

Open your web browser and navigate to http://localhost:3000. You should see "Hello, World!" displayed. In your terminal, you will also see the log from your middleware stating the HTTP method and URL of the request.

Customizing Your Middleware

Whenever you need to perform specific tasks, you can adjust your middleware. Here are few examples of what you can log or manipulate:

  • Log Headers:

    console.log(req.headers);
  • Check for Authorization:

    if (!req.headers.authorization) { return res.status(403).send('Forbidden'); }
  • Measure Request Duration:

    const startTime = Date.now(); next(); const duration = Date.now() - startTime; console.log(`Request took ${duration}ms`);

Conclusion of Middleware Use

By now, you've seen how easy it is to create a custom middleware in Express.js that enhances your application functionality while keeping your code clean and organized. Middleware is a powerful feature that you'll find essential as your application grows. Don't hesitate to explore even more complex middleware tailored to your application's specific needs!

Share now!