Languages
[Edit]
EN

Express.js - add/set session variables

0 points
Created by:
Geospatial-Palus
630

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

See also

  1. Express.js - create session 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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