Utilisez session Express.js .
Cela vaut également la peine de jeter un œil à Passport.js ce qui rend la mise en œuvre de l'authentification dans Node.js vraiment facile.
Exemple de session 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();
}
});