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.
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
.
xxxxxxxxxx
1
const express = require('express');
2
const session = require('express-session');
3
const app = express();
4
5
app.use(
6
session({
7
secret: 'replace this value with secret string ...' // it is good to use random string
8
})
9
);
10
11
app.get('/login', (request, response) => {
12
const username = request.body.username;
13
const password = request.body.password;
14
// authentication
15
if (isCorrect) {
16
request.session.loggedin = true; // Initializing session variable - loggedin
17
} else {
18
response.send('Incorrect Username and/or Password!');
19
}
20
);
21
22
app.get('/protected-path', (request, response) => {
23
if (request.session.loggedin) { // reading loggedin variable
24
response.send('Secret content - only for logged users');
25
} else {
26
response.send('Please login to view this page!');
27
}
28
response.end();
29
);
30
31
app.listen(3000);

