Skip to main content

Command Palette

Search for a command to run...

Express Js Middleware

Middleware is like checkpoints for the request to check, modify, and log for requests before it reaches the request handler function.

Updated
5 min read
Express Js Middleware

Let's understand it in a short story, suppose you want to issue a book from a library then you have to go through some checkpoints, so consider those as middleware. First, you will be checked to know whether you are authenticated to access college premises, and then the librarian will check your authorization by your library card after that she will log your request and you will get your book, This is where the middleware plays an important role.

Middleware

Defining middleware is very easy in Express JS it takes three parameters req, res and next and only in error handling middleware we have one extra parameter that is err .

/** req object represents the HTTP request made by the client to the server */
/** res object represents the HTTP response that the server will send back to the client */
/** next  function is used to pass control to the next middleware function in the stack */
app.use((req, res, next) => { });

Types of middlewares

As per the above example we can say middleware has many purposes to serve, we can categorize it into four types, Application level, Route level, Error handling, Built-in, and Third-party middleware

  1. Application level
    As we have seen in the above example if you want to enter the college premises, you will need an ID card for authentication so we can use the application-level middleware to check for the authenticated requests.

     /**Importing the express Js */
    
     const express = require('express');
    
     /** Initializing the express application */
    
     const app = express();
    
     /**Applying application level middleware */
    
     app.use((req, res, next) => {
         /**Logic to check user is authenticated or not */
         next()
     });
    
  2. Route level

    In the library, some sections are reserved for the college staff, so some areas are inaccessible even if you have an ID card(Authenticated user). To achieve this in express Js we need to secure those routes from other users to achieve this we will use Route level middleware.

     /** Importing the express Js */
     const express = require("express");
    
     /** Creating a new instance of router. */
     const router = express.Router();
    
     /**
     * Route level middleware are bound to an instance of express.Router().
     */
     router.use((req, res, next) => {
         /**Logic to validate whether a user is staff or not */
         next()
     });
    

    There are a few more examples of route-level middleware that will help us

    drill down to use middleware more effectively. We can say that we want to add a validation that a user can only issue a book of the course he/she has opted for to achieve this in express we will use the below code.

     /**
     * Middleware that will be applied on /books/stream/:streamName and /books/stream/:streamName/zyz
     */
     router.use('/books/stream/:streamName',(req, res, next) => {
         /**Logic to validate stream based on stream name and user */
         next();
     });
    
  3. Error handling

    Error-logging middleware can be easily identified by an extra parameter in the middleware function, it is one of the default features provided by Express Js. We can use this feature whenever we have to throw an error.

     /**Registering a middleware to catch and log error and return 500 to users*/
     app.use((err, req, res, next) => {
       console.error(err.stack);
       res.status(500).send('Something went wron');
     })
    
  4. Built-in

    Express provides several built-in middleware functions that help handle common tasks in web development, we will see a few examples of built-in middleware.

     /*
     * Used to convert JSON data in request to Javascript object and can be accesed by req.body
     * Used when Content-Type is application/json mainly in REST API's
     */
     app.use(express.json());
    
     /**
     * Used when user submit a web form with Content type application/x-www-form-urlencoded
     * To convert the urlencoded data into Javascript object.
     */
     app.use(express.urlencoded({ extended: true }));
    
     /**
     * Used to serve static files (HTML, CSS, JS, Images)from the public folder.
     * You can sepecify any other folder of you choice also.
     */
     app.use(express.static('public'));
    
  5. Third-party

    There are many library available to simplify web development, so we don’t have to write everything from scratch. Instead, we can use these features by simply installing them with npm. We will see to most common example of third-party middleware.

     /** CORS Middleware */
     /** Allows your server to handle requests from different origins, which is essential for enabling Cross-Origin Resource Sharing (CORS). */ 
     /** npm install cors */
     const express = require('express');
     const cors = require('cors');
     const app = express();
    
     /** Use CORS middleware to allow requests from any origin */
     app.use(cors());
    
     app.get('/', (req, res) => {
       res.send('CORS is enabled for all origins!');
     });
    
     /** Parses cookies attached to the client request object and makes them available via req.cookies.*/
     /** Cookie parser middleware */
     /** npm install cookie-parser */
     const express = require('express');
     const app = express();
     const cookieParser = require('cookie-parser');
     /** Adding cookieParser middleware */
     app.use(cookieParser());
    

Conclusion

In summary, middleware in Express.js acts like checkpoints in a library, performing various tasks to ensure smooth operations. From application-level checks like authentication to route-level validation and error handling, middleware helps manage requests and responses efficiently. Built-in middleware such as express.json() and express.static() streamline common tasks, while third-party middleware like cors and cookie-parser enhance functionality with minimal setup. By understanding and utilizing these middleware types, you can build robust, well-organized web applications that handle various scenarios seamlessly.

Express Js

Part 1 of 3

In this series, we’ll explore Express JS from basics to advanced. Learn routing, middleware, ORM, and user authentication with Passport.js, REST API, and Stripe.js payment integration.

Up next

Routing in Express Js

In this article, we will learn about routing in Express Js that we will use whether we are developing REST API or full-stack applications. Let's understand, why we need routing and how it will help us to manage application code better and also help i...

More from this blog

A

Abhishek Jha

15 posts

As a Full Stack Developer with four years of extensive expertise in the field of PHP, Laravel, MySQL, Linux, HTML, JavaScript, Jquery & Vue