Skip to content

Instantly share code, notes, and snippets.

@HarshithaKP
Last active February 12, 2022 09:19
Show Gist options
  • Save HarshithaKP/3d9ad81138245aa7527bf385d37daba7 to your computer and use it in GitHub Desktop.
Save HarshithaKP/3d9ad81138245aa7527bf385d37daba7 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}`)
})
})
})
@husanGuru
Copy link

@HarshithaKP
I was trying to do it with async/await, and having problems.
This works fine, thanks.
How it can be done with async/await ?

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