Sitemap
Samwuel simiyu

Samwuel simiyu

Demystifying middleware in Nodejs

2 min readDec 14, 2023

In Layman’s language…

Get Samwuel simiyu’s stories in your inbox

Join Medium for free to get updates from this writer.

So i’ll try to explain middleware in layman’s language. So it’s easier for you to understand. So now think of middleware as a series of workers in a factory assembly line. Each worker (middleware) performs a specific task on a product (the request) before passing it along to the next worker or finishing the product. Make sense right?

Press enter or click to view image in full size

So let’s break everything down:

  1. Assembly Line (Request-Response Cycle): Imagine a conveyor belt where products move from one end to another. In Node.js, this is like the journey of a request through your application to get a response.
  2. Workers (Middleware Functions): These are the workers stationed along the assembly line. Each worker receives a product (request), the worker then does something specific with the product it receives. For instance, one worker might check if the product has all the necessary parts (authentication), another might add a sticker (logging), and so on.
  3. Passing Along the Product: After a worker finishes its job, it hands over the product to the next worker in line (calls the next() worker). This happens until the product reaches the end of the line (response is sent back).
  4. Adding or Modifying the Product: Workers can modify the product as needed. For instance, a worker might add more details to the product, change its appearance, or decide it’s incomplete and reject it (end the process).
  5. Error Handler: Just like a quality checker at the end of the assembly line, there’s someone (an error-handling middleware) who catches any faulty products (errors) and deals with them appropriately.

Below is a code example to show the entire process.

const express = require('express');
const app = express();

// Middleware function - Logging incoming requests
app.use((req, res, next) => {
console.log(`Incoming request: ${req.method} ${req.url}`);
next(); // Pass control to the next middleware function
});

// Route-specific middleware - Handling GET request to '/'
app.get('/', (req, res) => {
res.send('Hello, World!');
});

// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});

// Starting the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});
  • The first middleware logs incoming requests.
  • There’s a route-specific middleware that handles GET requests to the root URL ('/').
  • An error-handling middleware catches and handles errors, sending an error response if something goes wrong.

Just as workers perform specific tasks in a factory, each middleware function in the code above performs its specific task in the Node.js application’s request-response cycle. They work together to handle incoming requests, execute specific functionalities, and deal with errors if they occur.

I hope i have made it much simple for you to understand the middleware concept. If you have any questions, feel free to reach out so we can solve it.

--

--

Chess Coach, Software Developer, Teacher.

See more from me