You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
12 Hrs
40 Min
27 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Middlewares - logger

13/30
Resources

Implementing middleware in Express is a powerful tool for managing the flow of requests in your application. These components allow you to execute specific code during the lifecycle of an HTTP request, offering the possibility to perform actions such as logging, authentication or error handling before the response is sent to the client. Mastering this concept will give you more control over your API and significantly improve the quality of your web applications.

What are middlewares in Express and why are they important?

Middlewares are functions that are executed during the lifecycle of an HTTP request in Express, before the response is sent to the user. They act as intermediaries that can perform various tasks without the end user noticing these additional processes.

These functions have access to:

  • The request object (req)
  • The response object (res)
  • The next() function that allows to continue to the next middleware or route.

Middlewares are fundamental because they allow:

  • Record information of each request (logging)
  • Implement authentication systems
  • Centralized error handling
  • Encapsulate common logic before processing a request

A well-implemented middleware can help you detect anomalous behavior, such as a sudden increase in requests that could indicate an attack, or simply provide valuable information about the use of your API.

How to create a logging middleware in Express?

To implement a middleware that logs information about each request that arrives to our API, we will follow these steps:

Project structure

First, we create a proper structure for our middleware:

  1. We create a folder called "middlewares" in the root of our project.
  2. Inside this folder, we create a file called "logger.js".

Implementation of the logging middleware

In the logger.js file, we implement our middleware with the following code:

const loggerMiddleware = (req, res, next) => { // We capture the time when the request arrives const timestamp = new Date().toISOString();  
 // We log information from the incoming request console.log(timestamp, req.method, req.url, req.ip);  
 // We measure the response time const start = Date.now();  
 // We listen for the 'finish' event to know when the response ends res.on('finish', () => { const duration = Date.now() - start; console.log(timestamp, 'response', res.statusCode, duration + 'ms'); });  
 // We move to the next middleware or path next();};
module.exports = loggerMiddleware;

This middleware captures crucial information such as:

  • The exact time of the request.
  • The HTTP method used (GET, POST, DELETE, etc.)
  • The URL requested
  • The IP address of the client
  • The status code of the response
  • The duration of the request in milliseconds

Integration of the middleware in the application

To use our middleware in the main application, we must import and register it:

const express = require('express');const loggerMiddleware = require('./middlewares/logger');
const app = express();
// We register the middleware to run on all requestsapp.use(loggerMiddleware);
// Rest of the application's paths and settings.

It is important to note that the next() function is crucial in the middleware, as it allows execution to continue to the next middleware or route. Without this call, the application would be "hung" and would never complete.

What are the benefits of a logging system in your API?

Implementing a logging system like the one we have created provides multiple advantages:

Monitoring and diagnostics

  • Complete visibility: You can see all requests coming to your API, including methods, routes and response times.
  • Problem detection: Quickly identify routes that are generating errors (4xx or 5xx codes).
  • Performance analysis: Detect slow endpoints that need optimization.

Security

  • Suspicious activity detection: A sudden increase in the number of requests could indicate an attack attempt.
  • IP logging: Identify the source of potentially malicious requests.
  • Auditing: Maintain a history of all interactions with your API.

Continuous improvement

  • Usage patterns: Identify the most used routes to optimize them.
  • Performance metrics: Evaluate the average response time of your API.
  • Integration with external services: This information can be sent to specialized services for further analysis.

The middleware we have created is just the beginning. You can expand it to capture additional information from the req object according to your specific needs, or even send these logs to external services for storage and analysis.

Middlewares are a versatile tool that can adapt to multiple use cases, from simple logging to complex authentication and authorization systems, becoming an essential component in the development of robust APIs with Express.

Have you implemented middleware in your Express projects? Share in the comments how you have used them and what additional features you would like to learn how to implement.

Contributions 1

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

En mi caso utiliza `toLocaleString() `para entender un por mejor el formato de la fecha: algo tipo: *7:35:44 PM - GET /users - IP ::1*