Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Middleware in Express.js

Middleware in Express.js

Middleware in Express.js is a fundamental concept that allows you to perform actions on the request and response objects, as well as modify them, before they reach their final destinations (routes or handlers). This makes it a powerful tool for tasks like authentication, error handling, data parsing, and more.

Here's an overview of how middleware works in Express.js:

Middleware Functions:

A middleware function is a JavaScript function that takes three arguments: req (request object), res (response object), and next (a callback function). It can perform operations on the request and response, and either terminate the request-response cycle or pass control to the next middleware or route handler.

const myMiddleware = (req, res, next) => {
  // Perform operations on req and res
  // ...
  
  // Call next to pass control to the next middleware or route handler
  next();
};
 

Using Middleware:

Middleware can be used at the application level or at the route level.

1. Application-Level Middleware:

Application-level middleware is defined using app.use() and is executed for every request made to the server.

app.use(myMiddleware);
 

2. Route-Level Middleware:

Route-level middleware is applied to specific routes and is executed only when the specified route is matched.

app.get('/someRoute', myMiddleware, (req, res) => {
  // Route handler logic
});

 

Example Use Cases for Middleware:

1. Logging Requests:

  • Middleware can log details about each incoming request, such as the request method, URL, and timestamp.

2. Authentication:

  • Middleware can verify if a user is authenticated before allowing access to certain routes.

3. Error Handling:

  • Middleware can catch errors and send appropriate error responses to clients.

4. Parsing Request Data:

  • Middleware can parse request bodies (e.g., JSON, form data) and make it available in req.body.

5. Authorization:

  • Middleware can check if a user has the necessary permissions to access a particular resource.

6. Handling CORS (Cross-Origin Resource Sharing):

  • Middleware can handle CORS headers to control which domains are allowed to access resources.

Example Middleware Function for Logging Requests:

const logRequest = (req, res, next) => {
  console.log(`Received ${req.method} request for ${req.url} at ${new Date()}`);
  next();
};

app.use(logRequest);
 

In this example, logRequest is a middleware function that logs information about each incoming request. It is then applied at the application level using app.use().