Skip to content

Instantly share code, notes, and snippets.

@destiny0114
Created July 9, 2020 07:52
Show Gist options
  • Save destiny0114/27a5ee5d86866d79307dda321d03a691 to your computer and use it in GitHub Desktop.
Save destiny0114/27a5ee5d86866d79307dda321d03a691 to your computer and use it in GitHub Desktop.
track user how many times view the page
var express = require('express')
var parseurl = require('parseurl')
var session = require('express-session')
var app = express()
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
app.use(function (req, res, next) {
if (!req.session.views) {
req.session.views = {}
}
// get the url pathname
var pathname = parseurl(req).pathname
// count the views
req.session.views[pathname] = (req.session.views[pathname] || 0) + 1
next()
})
app.get('/foo', function (req, res, next) {
res.send('you viewed this page ' + req.session.views['/foo'] + ' times')
})
app.get('/bar', function (req, res, next) {
res.send('you viewed this page ' + req.session.views['/bar'] + ' times')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment