Introducci贸n a Node.js y Express
Node.js y Express
Entorno de trabajo
Variables de entorno
Rutas din谩micas
Body parser
Postman
CRUD
驴Que es una API Restful?
Solicitudes GET
Solicitudes POST
CRUD
Soluci贸n del reto de validaci贸n
Solicitudes DELETE
MIddlewares
Middlewares - logger
Middlewares - ErrorHandler
DB
Instalar Postgresql
Instalar Prisma y PostgreSQL Client
Prisma Models
JWT
Autenticaci贸n utilizando JSON Web Tokens (JWT)
Auth - Register
Auth - Login
Expres.js
Arquitectura
Arquitectura parte 2
Creaci贸n y Migraci贸n de Modelos con Prisma para Citas M茅dicas
Admin controllers / services
Admin controllers / services parte 2
Reservations
Reservations parte 2
Appointments
Deploy
PostgreSQL
Deploy
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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:
Middlewares are fundamental because they allow:
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.
To implement a middleware that logs information about each request that arrives to our API, we will follow these steps:
First, we create a proper structure for our 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:
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.
Implementing a logging system like the one we have created provides multiple advantages:
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
Want to see more contributions, questions and answers from the community?