EN
Express.js - add/set session variables
0
points
In this article, we would like to show you how to add session variable using express-session module in Express.js.
Practical example
The example below shows the creation of the loggedin
session variable in which we store information whether the user is logged in or not. Access to protected paths will be granted only to the users whose request.session.loggedin
value is true
.
const express = require('express');
const session = require('express-session');
const app = express();
app.use(
session({
secret: 'replace this value with secret string ...' // it is good to use random string
})
);
app.get('/login', (request, response) => {
const username = request.body.username;
const password = request.body.password;
// authentication
if (isCorrect) {
request.session.loggedin = true; // Initializing session variable - loggedin
} else {
response.send('Incorrect Username and/or Password!');
}
);
app.get('/protected-path', (request, response) => {
if (request.session.loggedin) { // reading loggedin variable
response.send('Secret content - only for logged users');
} else {
response.send('Please login to view this page!');
}
response.end();
);
app.listen(3000);