Search⌘ K
AI Features

Creating Custom Middleware

Explore how to create and organize custom middleware in Express.js to intercept and modify requests and responses. Understand middleware stacking, attaching middleware directly to routes, and implementing robust error handling to build maintainable and secure backend applications.

Middleware functions are the backbone of an Express.js application. They allow us to intercept requests, modify data, and control the flow between incoming and outgoing responses.
While built-in and third-party middleware provide useful functionality, we often need to create custom middleware to address specific application needs, including:

  • Logging

  • Authentication

  • Validation

  • Error handling

  • Data transformation

  • Response modification

  • Security enforcement

In this lesson, we’ll focus on writing custom middleware, organizing middleware for reusability, and implementing effective error handling.

Designing and writing custom middleware

Custom middleware makes writing reusable code easier, simplifying requests and adding features tailored to your app. For instance, this middleware function converts all response object keys to uppercase before sending them back to the client.

{
  "name": "node-server",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "test": "mocha"
  },
  "dependencies": {
    "async": "^3.2.4",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "mocha": "^11.1.0",
    "supertest": "^7.0.0"
  }
}
Transforming API responses with custom middleware

Explanation:

  • Line 4: This defines the transformResponse middleware function, which takes reqres, and next as parameters.

  • Line 5: This stores the original res.json method.

  • Lines 7–11: This replaces the original res.json method to transform response data by converting all keys to uppercase before sending it to the client. The transformation uses reduce() with an ...