Single route middleware to check if User is Authenticated using Node.js

Middleware is a function with access to the request object (req), the response object (res),
and the next middleware in the application’s request-response cycle, commonly denoted by a variable named next. You can read more about this Here. route middleware nodejs

Its difficult to call function in each route and check if user authenticated or not so I found the way somewhere where we can use routes
Middleware to prevent calling function each and every routes which I am going to share with you today.

Our Route looks like this:-

var express = require('express');
var router = express.Router();

//all routes
router.get('/home',function (req, res) {
res.render('home.html');
});

Now create a Route Middleware function to check if user authenticated

function isUserAuthenticated(req,res,next){
//you can check anything heref like req.url ,session ect.

//so let's check if user session exists
if(req.session.user){
//user logged in
return next();
}
//user not authenticated redirect them to login page or anywhere you want
res.redirect("/login");
}

Now we have the function to check if user authnticated its time to implement that you can use this like below:-

//all routes
router.get('/home', isUserAuthenticated, function (req, res) {
res.render('home.html');
});

One Comment

  1. LorrineSt March 2, 2017 Reply

Add a Comment

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