Patrones de dise帽o en Node.js
Qu茅 es Node.js y c贸mo impulsa tu negocio
Patrones de dise帽o esenciales en Node.js
Patr贸n Singleton y Factory en JavaScript
Implementaci贸n pr谩ctica de Singleton y Factory en JavaScript
Implementaci贸n del patr贸n Observer con EventEmitter en Node.js
Implementaci贸n de Middlewares en Node.js sin Express
Decorators e inyecci贸n de dependencias en JavaScript
Flujo de Datos con Node.js
Aprende qu茅 son Buffer y Streams en Node.js
C贸mo utilizar streams y pipelines en Node.js
C贸mo funciona el Event Loop en Node.js
Qu茅 es Libuv y c贸mo maneja la asincron铆a en Node.js
Estrategias para ejecutar c贸digo as铆ncrono en Node.js
Debugging y Diagn贸stico en Node.js
C贸mo utilizar el Debugger en Node.js para solucionar problemas
Uso de Diagnostic Channels en Node.js para observabilidad y diagn贸stico
Instrumentaci贸n y m茅tricas clave en performance para aplicaciones Node.js
Control de errores globales y manejo de se帽ales en Node.js
Implementaci贸n Eficiente de Logs con Pino en Node.js
Performance en Node.js
An谩lisis del event loop en aplicaciones Node.js usando Nsolid
C贸mo Diagnosticar y Solucionar Memory Leaks en Aplicaciones Node.js
Optimizar rendimiento en Node.js con Worker Threads y Child Processes
Optimiza y Escala Aplicaciones Node.js con T茅cnicas de Caching
Creando CLIs con Node.js
C贸mo crear aplicaciones CLI con Node.js
C贸mo Crear un CLI con Minimist y Manejar Argumentos en Node.js
Creaci贸n de un CLI con Node.js y Google Generative AI
Creaci贸n de Chat con IA usando CLI en Node
C贸mo Crear e Instalar tu Propio CLI de Node con npm
You don't have access to this class
Keep learning! Join and start boosting your career
Learning how the Middleware pattern works in Node.js allows you to sequentially execute operations during a request. Although Express is known for using this pattern extensively, it is possible to implement it from scratch in Node.js. It is basically functions that manipulaterequests andresponses and can modify, add or remove properties depending on their function.
Middleware is a simple but powerful technique that allows you to handle Web requests by splitting the processing into independent stages. It is central to frameworks such as Express and consists of functions that are executed one after the other in a chain.
A middleware receives three main arguments:
Each Middleware can alter or enrich the objects received before passing them to the next one.
Implementing your own Middlewares without Express is an effective way to understand its inner workings. Here is a quick description of how to perform a basic implementation using only Node.js.
Declare a function called runMiddlewares
that accepts request, response and an array of Middlewares.
Each Middleware is a separate, clearly identifiable function:
const middleware1 = (req, res, next) => { console.log('Middleware1 - Authentication'); next(); }; const middleware2 = (req, res, next) => { console.log('Middleware2 - Request processing'); next(); }; const middleware3 = (req, res, next) => { console.log('Middleware 3 - Completion'); next(); }; const middleware3 = (req,res, next) => { console.log('Middleware 3 - Completion'); next();};
Each Middleware is executed in sequential order using a recursive function:
const runMiddlewares = (req, res, middlewares) => { let index = 0; const next = () => { if (index < middlewares.length) { const middleware = middlewares[index++]; middleware(req, res, next); } xml-ph-0030@de
Finally, you must start this process by specifying the required parameters:
const req = {};const res = {};runMiddlewares(req, res, [middleware1, middleware2, middleware3]);
Middlewares are executed strictly in the order in which they are defined in their array. This allows for easy control of specific functionalities, such as authentication, validation, main processing and termination. This ensures that the logical order required for each task is followed.
As a further exercise, you can extend this implementation with conditional logic. For example, allow Middleware 3 to control the execution of Middleware 4:
This exercise brings an additional layer of real-world utility to your middleware knowledge.
Try building your own version and share it!
Contributions 3
Questions 0
Want to see more contributions, questions and answers from the community?