What is a Session?

The Session is a container to store data that you want access to across requests. Each user that visits your website has a unique session.  You can use sessions to store and access user data as they browse your application.

Sessions are an integral part of web application development because they allow the application to store state. Based on what action a user took on Page A, we can show a different Page B. Without them, applications would be stateless, and not very useful.

Why Session important?

Each and Every web application that maintains user data has to deal with sessions. Being developers, We need to know what they are and how to use them.

As we all know,  HTTP is a stateless protocol. in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both transport data between the client and the server. But they are both readable and on the client side. Sessions solve exactly this problem.

We will need to install some modules, so install them using the following code.

npm install --save express
npm install --save body-parser
npm install --save ejs
npm install --save express-session

Example

server.js File

var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);

app.use(session({secret: 'user'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

var sess;

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

if(sess.email) {

    res.redirect('/admin');
}
else {
    res.render('index.html');
}
});

app.post('/login',function(req,res){
  sess = req.session;

  sess.email=req.body.email;
  res.end('done');
});

app.get('/admin',function(req,res){
  sess = req.session;
if(sess.email) {
res.write('<h1>Hello '+sess.email+'</h1>');
res.end('<a href="/logout">Logout</a>');
} else {
    res.write('<h1>Please login first.</h1>');
    res.end('<a href="/logout">Login</a>');
}
});

app.get('/logout',function(req,res){
req.session.destroy(function(err) {
  if(err) {
    console.log(err);
  } else {
    res.redirect('/');
  }
});

});
app.listen(3000,function(){
console.log("App Started on PORT 3000");
});

Project Directory Structure :

views/Index.html

<html>
<head>
    <title>Session</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            var email, pass;
            $("#submit").click(function () {
                email = $("#email").val();
                pass = $("#password").val();
                $.post("http://localhost:3000/login", { email: email, pass: pass }, function (data) {
                    if (data === 'done') {
                        window.location.href = "/admin";
                    }
                });
            });
        });
    </script>
    <style>
        tr,
        td {
            padding: 10px
        }

        #form {
            background-color: beige;
            margin-top: 30px;
            border-radius: 10px
        }
    </style>
</head>
<body>
    <div class="col-md-4"></div>
    <div class="col-lg-4" id="form">
        <form>
            <table>
                <tr>
                    <td>Username</td>
                    <td>
                        <input type="text" size="40" placeholder="Enter Your Name" id="email" class="form-control">
                    </td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td>
                        <input type="password" size="40" placeholder="Enter Your Password" id="password" class="form-control">
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type="button" value="Submit" id="submit" class="btn btn-primary">
                        <input type="reset" value="Reset" class="btn btn-danger">
                    </td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>

Get More Knowledge: