Languages
[Edit]
EN

Node.js / Express.js - add/set session variables

0 points
Created by:
Geospatial-Palus
420

In this article, we would like to show you how to add session variable using express-session module in Express.js.

Check this article to learn how to create an express.js session - link.

Session variables are used to store information that will be available from the time this variable is created until the session is destroyed. Most often these are information such as - user is logged in - we can also store data there how often the user accessed our website, etc.

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 logged-in users.

const express = require('express');
const session = require('express-session');
const app = express();

app.use(
    session({
        secret: 'secret',
    })
);

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);
User is not logged in
User is not logged in
 Protected page for logged in users
Protected page for logged in users

Node.js / Express.js - session management

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join