Yitong Zhou
Yitong Zhou

Reputation: 1175

nodejs, how to check if session is defined on every page

I am using express to develop a simple website. I just get confused about how to make the nodejs check session before rendering any page, so that if a user did not login, he cannot see anything.

I think in rails it is quite simple, just add some codes in the application controller. But how to handle such thing in nodejs?

Upvotes: 1

Views: 4463

Answers (1)

Hector Correa
Hector Correa

Reputation: 26690

Define a middleware function to check for authentication before your routes and then call it on each of your routes. For example in your app.js

// Define authentication middleware BEFORE your routes
var authenticate = function (req, res, next) {
  // your validation code goes here. 
  var isAuthenticated = true;
  if (isAuthenticated) {
    next();
  }
  else {
    // redirect user to authentication page or throw error or whatever
  }
}

Then call this pass this method in your routes (notice the authenticate parameter):

app.get('/someUrl', authenticate, function(req, res, next) {
    // Your normal request code goes here
});

app.get('/anotherUrl', authenticate, function(req, res, next) {
    // Your normal request code goes here
});

Upvotes: 6

Related Questions