Express Complete tutorial : Part 4

Session is very important for any web application. Session handling help us to track the user activity and also to allow or disallow user to access particular part of web app.

In last tutorial i have explained about routing of express application. In this i am going to explain session handling in Express.

Handling Session in Express is not a big deal either, you have to use “express-session” middle-ware in order to handle Session in Express.

npm install --save express-session

We have already configured this in our first tutorial of Express Series.

We can access the Session using Request of Express instance. For.eg

var app=express();
var sess;
app.get('/',function(req,res){

/*
   By using 'req' we can initialize session.
*/

 
sess=req.session; //Session initialized.

//Now by using 'sess' we can create session variables.
//for.eg
sess.email="[email protected]";//OR
sess.id="1000";

});

I am going to cover some cases where Session can be used.

Case 1 : Initialize Session When user visits Home page.
Code:

var sess;
app.get('/',function(req,res){
sess=req.session;
});

Case 2 : Set Session variable to ’email’ by which User have logged in.
Code:

var see;
app.get('/login',function(req,res){
sess=req.session;
/*
   Logic to check user log-in details.
*/

if(user_have_logged_in)
{
    sess.email=req.body.email;
    //Assuming email and password comes from Client.
    res.json({"yes":"1"});
}
else
{
     res.json({"yes":"0"});
}
});

Case 3 : Redirect User to home page if not log-in and trying to access profile.
Code:

//Assuming, user can view profile only if log-in.
//If user log-in then sess.email must be set.
//We can check it to validate the session.
var sess;
app.get('/profile',function(req,res){
   
     sess=req.session;
     if(sess.email)
     {
         res.render('profile',{email:sess.email});
     }
     else
     {
         res.redirect('/');
     }
});

Case 4 : Destroying Session after user log out.
Code:

var sess;
app.get('/logout',function(req,res){
     sess=req.session;
     if(sess.email)
     {
         //We will destroy the session now.
         req.session.destroy(function(err){
         if(err)
         {
             console.log(err);
         }
         else
         {
             //Session destroyed, redirect to home page.
             res.redirect('/');
         }
     }
     else
     {
        res.redirect('/');
     }
});

There are many possibilities where you can use the session. But basic idea is

  • initialize session.
  • set session variable if it’s first time.
  • check session variable to validate the Session.

For complete code and information you can read the detail tutorial from scratch here.

In next tutorial i am going to explain how to deploy your express app and finalizing some important settings. Stay tuned.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126