Skip to content

Instantly share code, notes, and snippets.

@mike-schultz
Created August 17, 2016 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mike-schultz/3acb2224d91d6475146fcfbc43b7aaa5 to your computer and use it in GitHub Desktop.
Save mike-schultz/3acb2224d91d6475146fcfbc43b7aaa5 to your computer and use it in GitHub Desktop.
Simple express session demo
{
"name": "sample-node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"connect-mongo": "^1.3.2",
"express": "^4.14.0",
"express-session": "^1.14.0"
}
}
var express = require('express');
var app = express();
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
app.use(session({
name: 'my-session',
cookie: {
//Current Server time + maxAge = expire datetime
maxAge: 1000 * 60,
//Allows for the cookie to be read only by a server (no JS)
httpOnly: false,
//Set for the root of the domain.
path: '/',
},
secret: 'foobarbazfizzbuzz',
store: new MongoStore({
url: 'mongodb://localhost/sample-node'
})
}));
app.use((req,res,next) => {
var visit = req.session.visit;
if(!visit) {
visit = req.session.visit = {
count: 1
}
} else {
visit.count++;
}
next();
});
app.get('/', (req, res) => {
res.send('you viewed this page ' + req.session.visit.count + ' times')
})
app.listen(3000);
var express = require('express');
var app = express();
var session = require('express-session');
app.use(session({
name: 'my-session',
cookie: {
//Current Server time + maxAge = expire datetime
maxAge: 1000 * 60,
//Allows for the cookie to be read only by a server (no JS)
httpOnly: true,
//Set for the root of the domain.
path: '/',
},
secret: 'foobarbazfizzbuzz'
}));
app.use((req,res,next) => {
var visit = req.session.visit;
if(!visit) {
visit = req.session.visit = {
count: 1
}
} else {
visit.count++;
}
next();
});
app.get('/', (req, res) => {
res.send('you viewed this page ' + req.session.visit.count + ' times')
})
app.listen(3000);
var express = require('express');
var app = express();
app.get('/', (req, res) => {
res.send('Hello world!');
});
app.get('/foo', (req, res) => {
res.send('You navigated to foo!');
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment