Middleware in Node Js & Express | How to create authentication Middleware in Node Js & Express

Express is an routing and middleware framework. And we use express to managing the routes and middlewares. Also it provides some folder structures.

Middleware is something which you wanted to execute before executing any particular function. For example we need a login check before accessing the user  dashboard and logout. That check is called middleware here.

In Express framework middleware has access to req (Request), res (Response) and next (Next route).

We validate the data through the request and if validation is true then return to the next action else we return to any URL like login using res (Response).


Now how to use this middleware look at below code.

Now here in this logout function we have passed Guard.isAuthenticated this will check the middleware code first.

In middleware.js we have checked if there is user session then return next URL like logout else return to login.

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *