Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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}`)
})
})
})
@HarshithaKP

This comment has been minimized.

Copy link
Owner Author

@HarshithaKP HarshithaKP commented Nov 8, 2019

Output :

first timer : 1
first response : first timer
subsequent views: 2
in redirected route, views:  2 and extra: some extra data
second response : redirected response
@umakanth-pendyala

This comment has been minimized.

Copy link

@umakanth-pendyala umakanth-pendyala commented Oct 24, 2020

I did the exact same thing u are doing in my project.But it is not working.

@umakanth-pendyala

This comment has been minimized.

Copy link

@umakanth-pendyala umakanth-pendyala commented Oct 24, 2020

Here. Take a look at my issue please. expressjs/session#790

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment