Express middlewares in 2 min

Dikshant Rajput
3 min readSep 17, 2022

In the previous blog, I explained about getting started with express.js in 2 min. In this blog, I will be explaining about express middlewares.

Middleware is something that handles one of the most important business logic of any application whether it is related to authorization or authentication or logging or any other use case like adding something to the request.

In lamen terms, middlewares are the thing that basically sits like a middleman between the request and the response.

middleware

Express and middlewares go hand in hand. Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls. (acc to express docs).

Creating a middleware in Express and using it in your routes is not a difficult task. So without wasting a second, let’s get started.

We will be creating a middleware that will provide authentication to our APIs from a token and if invalid or no token is provided, it won’t let the request go further and will throw an unauthorized error upfront.

Create a login route that will accept email and password and if that is correct we will generate a token and for now we will be using static values and not from any db.

  • /login

User will get a token after login that he will have to use in the protected routes. For this we will create an authMiddleware something like this

We will check for authorization header and if we get correct value, we will let the user request go further. generally in this middleware, if you have used jwt then jwt verification will happen or something similar to checking user request and deciding to let the request go further or not. Now the protected route will look something like this:

  • /protected

If you hit the endpoint ‘/protected’, you have to provide a Bearer token in authorization header and if token is not valid, you will get a 401 and if it is valid you will see the following response.

This way middleware can be very useful for

  • authenticating user
  • attaching attributes to request like user id or email etc.
  • logging requests
  • error handling
  • and many more…

That’s all about middlewares. I hope you like the blog and if you do then don’t forget to hit the clap icon and do follow me for more such blogs.

Drink water. Keep smiling…

--

--