How to Use Session Variable with Nodejs?

I have the following NodeJS code:

  let sql = `SELECT box_id, cubby_id, occupied, comport
           FROM box
           WHERE longestDimension = ?
           AND LOWER(box_id) = LOWER(?)`;

    connection.query(sql, [boxSelectedDimension, boxSelectedValue] , function(err, rows, fields) {
        if (!err) {
            for(var i=0; i< rows.length; i++) {
                // Make the comparaison case insensitive
                if (rows[i].occupied == `unoccupied`) {
                    console.log("free");

                    var comport = rows[i].comport;
                    var command = "open" + rows[i].cubby_id;

Essentially i would like to store the value of the comport and command variable in a session variable so that the value of these variable could be used in another router page in nodejs.

I am not sure how to store and retrieve the session variable.

2

1 Answer

Install express-session and use as follows:

var express = require('express');
var session = require('express-session');
var app = express();
app.use(session({secret:'XASDASDA'}));
var ssn ;
app.get('/',function(req,res){
    ssn=req.session;
   /*
   * Here we have assign the 'session' to 'ssn'.
   * Now we can create any number of session variable we want.    
   * Here we do like this.
   */
   // YOUR CODE HERE TO GET COMPORT AND COMMAND
   ssn.comport; 
   ssn.command; 
});

Following code explain simple login and logout using session. The session we initialize uses secret to store cookies. Hope this helps.

var ssn;
app.get('/',function(req,res) { 
  ssn = req.session; 
  if(ssn.email) {
    res.redirect('/admin');
  } else {
    res.render('index.html');
  }
});
app.post('/login',function(req,res){
  ssn = req.session;
  ssn.email=req.body.email;
  res.end('done');
});
app.get('/admin',function(req,res){
  ssn = req.session;
  if(ssn.email) {
    res.write('<h1>Hello '+ssn.email+'</h1>');
    res.end('<a href="+">Logout</a>');
  } else {
    res.write('<h1>login first.</h1>');
    res.end('<a href="+">Login</a>');
  }
});
app.get('/logout',function(req,res){
  req.session.destroy(function(err) {
    if(err) {
      console.log(err);
    } else {
      res.redirect('/');
    }
  });
});
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest