Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to count number of visits to a website using Express.js ?

  • Difficulty Level : Medium
  • Last Updated : 01 Jul, 2021

Session management can be done in node.js by using the express-session module. It helps in saving the data in the key-value form. In this article, we will see how to count the Number of views in Express Session in Express Js.

Prerequisites:

  • Basic knowledge of  Node.
  • Node.js installed (version 12+).
  • npm installed (version 6+).

To set up Node Project in Editor you can see here.

Installing requires modules:

npm install express
npm install express-session

 



Call API:

var session = require('express-session')

Example: This example illustrates the above approach.

app.js




// Call Express Api.
var express=require('express'),
  
// Call express Session Api.
session = require('express-session'),
  
app=express();
  
// Session Setup
app.use (
    session ({
  
        // It holds the secret key for session
        secret: "I am girl",
  
        // Forces the session to be saved
        // back to the session store
        resave: true,
          
          
        // Forces a session that is "uninitialized"
        // to be saved to the store
        saveUninitialized: false,
        cookie: {
    })
);
  
// Get function in which send session as routes.
app.get('/session', function(req, res, next) {
  
    if (req.session.views) {
          
      // Increment the number of views.
      req.session.views++
  
      // Print the views.
      res.write('<p> No. of views: ' 
          + req.session.views + '</p>'
      res.end()
    } else {
      req.session.views = 1
      res.end(' New session is started')
    }
  })
  
// The server object listens on port 3000.
app.listen(3000,function(){
    console.log("Express Started on Port 3000");
});

Run index.js file using the below command.

node app.js

Now to set your session, just open the browser and type this URL .

http://localhost:3000/session

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :