Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save frankhn/40209c4ab3086143bb821950d1ed7ad8 to your computer and use it in GitHub Desktop.
Save frankhn/40209c4ab3086143bb821950d1ed7ad8 to your computer and use it in GitHub Desktop.
How to create session cookies with Node.js + Express
var express = require('express'),
app = express(),
https = require('https'),
fs = require('fs'),
keys = require( "keygrip" )(['secret1', 'secret2']),
cookies = require( "cookies" );
// This line is from the Node.js HTTPS documentation
var options = {
key: fs.readFileSync('private_key_cert.pem'),
cert: fs.readFileSync('public_cert.pem')
};
app.use(cookies.express(keys));
app.get('/', function(req, res){
if (req.cookies.remember) {
res.send('Remembered :). Click to <a href="/forget">forget</a>!.');
} else {
res.send('<form method="post"><p>Check to <label>'
+ '<input type="checkbox" name="remember"/> remember me</label> '
+ '<input type="submit" value="Submit"/>.</p></form>');
}
});
app.get('/forget', function(req, res){
res.clearCookie('remember');
res.redirect('back');
});
app.post('/', function(req, res){
var minute = 60 * 1000;
if (req.body.remember) res.cookie('remember', 1, { maxAge: minute });
res.redirect('back');
});
// Create an HTTPS service
https.createServer(options, app).listen(443);
console.log('Express started on port %d', 443);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment