Skip to content

Instantly share code, notes, and snippets.

@benzerbett
Forked from HarshithaKP/SessionPersistence.js
Created April 17, 2021 21:49
Show Gist options
  • Select an option

  • Save benzerbett/c6b3017270cf3a578d4d038f70888964 to your computer and use it in GitHub Desktop.

Select an option

Save benzerbett/c6b3017270cf3a578d4d038f70888964 to your computer and use it in GitHub Desktop.
Demonstration of how user session can be persisted across redirects, with an express server and request client.
var express = require('express')
var session = require('express-session')
var app = express()
var r = require('request')
// By default cookies are disabled, switch it on
var request = r.defaults( { jar:true } )
app.use(session({ secret: 'keyboard cat',saveUninitialized : false, resave : false, cookie: { maxAge: 60000 }}))
app.get('/', function(req, res, next) {
if(!req.session.views) {
req.session.views = 1
console.log('first timer : '+ req.session.views)
res.end('first timer')
} else {
req.session.views++
console.log('subsequent views: ' + req.session.views)
req.session.extra = "some extra data"
// While sessions with memoryStore may work fine with multiple requests/redirects, external
// stores can cause race conditions - between next client request and the store, depending
// on who runs faster. So save the session explicitly, prior to the response/redirect.
req.session.save(function(err) {
if(err) {
res.end('session save error: ' + err)
return
}
res.redirect('/admin')
})
}
})
app.get('/admin', function(req, res, next) {
console.log(`in redirected route, views: ${req.session.views} and extra: ${req.session.extra}`)
res.end('redirected response')
})
app.listen(8000, () => {
request.get('http://localhost:8000', (err,res,body) => {
console.log(`first response : ${body}`)
request.get('http://localhost:8000', (err,res,body) => {
console.log(`second response : ${body}`)
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment