Gunakan sesi Express.js .
Sebaiknya lihat juga Passport.js yang membuat penerapan autentikasi di Node.js sangat mudah.
Contoh sesi Express.js:
var express = require('express');
var session = require('express-session');
var app = express();
// Make sure this is defined before any of your routes
// that make use of the session.
app.use(session({
secret: 'keyboard cat',
cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: false
}));
// Access the session as req.session
app.get('/login', function(req, res) {
req.session.user = 1;
res.end('User 1 is logged in, please go to the /discussion page.');
});
app.get('/discussion', function(req, res) {
var sess = req.session;
if (typeof sess.user === 'undefined') {
res.redirect('/login');
} else {
res.setHeader('Content-Type', 'text/html');
res.write('<p>user: ' + sess.user + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.end();
}
});