Skip to content

Instantly share code, notes, and snippets.

@HarshithaKP
Created December 26, 2019 11:05
Show Gist options
  • Save HarshithaKP/87b1258d6476d2e3f311ae502a3f6d66 to your computer and use it in GitHub Desktop.
Save HarshithaKP/87b1258d6476d2e3f311ae502a3f6d66 to your computer and use it in GitHub Desktop.
An Express demo that shows usage of multiple session types in a single application.
var express = require('express')
var app = express()
var session = require('express-session')
const port = 8000
// session for local clients
var s1 = session({ name: 'one', secret: 'abc'})
// session for remote clients
var s2 = session({ name: 'two', secret: 'def'})
app.get('/', (req, res, next) => {
// Instead of attaching to the express app,
// invoke the appropriate session middleware
// based on your conditions. In the callback
// the request object will have the session
// object attached to it.
// Remeber to save the session before responding
// Condition to select the right session
if(req.headers.host === `localhost:${port}`){
s1(req, res, () => {
if(!req.session.localViews){
req.session.localViews = 1
} else {
req.session.localViews++
}
req.session.client = 'local'
req.session.save(() => {
res.send(`Hello ${req.session.client} client! visits: ${req.session.localViews}`)
})
})
}
else {
s2(req, res, () => {
if(!req.session.remoteViews){
req.session.remoteViews = 1
} else {
req.session.remoteViews++
}
req.session.client = 'remote'
req.session.save(() => {
res.send(`Hello ${req.session.client} client! visits: ${req.session.remoteViews}`)
})
})
}
})
app.listen(port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment