Ways to maintain the value of req.session using express-session

Check out these lines of code:

const session = require('express-session');
const sessionConfig = {
   secret: 'somesecretkey', 
   cookie: {secure: false}, 
   resave: false, 
   saveUninitialized: false, 
   store: new mongostore({ mongooseConnection: mongoose.connection })
}

router.get('/', function(req, res, next) {

  let abc = req.session.user;
  let trueOrFalse = isset(abc);

  console.log(trueOrFalse);
  req.session.user = 1;
  req.session.save();
});

function isset(var1){
  if( typeof var1 !== 'undefined' ) {
     return true;
}
  return false;
}

I expect the output to display 'false' for the first time and 'true' on subsequent page refreshes. However, it always shows 'false', indicating that the value is not being retained.

Any assistance would be greatly appreciated.

Answer №1

It appears that the session middleware has not been included in your setup, causing incoming requests to bypass it. To rectify this, you can add the following code snippet to your main file (typically app.js):

var session = require('express-session');
app.use(session({
   secret: 'yoursecretkey', 
   cookie: {secure: false}, 
   resave: false, 
   saveUninitialized: false, 
   store: new mongostore({ mongooseConnection: mongoose.connection })
}));

// Your route handlers should follow below
app.use("/", routes);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular's window.onload event occurs when the page has finished

How can I achieve the equivalent of window.onload event in Angular? I am looking to fade out and remove my preloader, but only after all resources such as images are fully loaded. Using $viewContentLoaded alone does not cover this scenario since it indica ...

Why is the user's name showing as undefined? If I were to change the ID from "nam" to "name"?

I developed a basic messaging web application using node express socket.io. However, when I try to retrieve the user's name, it shows up as undefined. (Interestingly, if I modify the user id, then it works fine - but why is that?) app.js const app ...

Adding an image to a server through PHP in the TinyMCE editor

Currently, I am in the process of utilizing TinyMCE text editor for uploading images using PHP and JS database. However, I find myself perplexed when it comes to sending the image to the server. Below is the snippet of the JS code being used: <script ...

Tips for importing a different js file from an npm package without needing to include the entire node_modules path

When using the ES2016 import syntax to load the select2 library from an npm module via Webpack, everything works smoothly and the select2.js file is loaded from the node_modules directory. The node_modules directory also contains a full version of the lib ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

What is the best way to assess each item in an array and apply the useState() hook based on a specific condition

I am currently working on a simulation for a blackjack hand and have run into an issue with my code. The game follows these steps: users receive two random cards and a total point value, then click 'hit' to draw another random card from the deck. ...

The watermark feature in HTML may not appear when printed on every page

I'm facing an issue with adding a watermark style. The watermark displays only on the first page when attempting to print in Chrome. It works perfectly in Firefox and IE. <style type="text/css"> #watermark { color: #d0d0d0; font-size: 90pt; ...

Using jQuery, you can easily modify the color of a TD cell by applying the css properties assigned to the div element

I am attempting to implement a jQuery script that will execute upon the loading of the document. The objective is for the script to retrieve the background color of a div located within a td cell and apply it as the background color for the respective td c ...

Integrate actual credentials into S3Client using redux async thunk

My S3-like react application with redux is powered by AWS SDK v3 for JS. The client initialization in my auth.js file looks like this: auth.js export const s3Client = new S3Client({ region: 'default', credentials: { accessKeyId: 'te ...

Create a single line of content for a carousel display

Seeking a solution where I can have a container that slides sideways without stacking in rows, I have exhaustively searched for answers using different keywords like single row, inline, flexbox, and grid but to no avail. Any assistance will be highly appre ...

Verifying internet connectivity and updating content using jQuery and JavaScript

Upon loading the page, the following functionality occurs without triggering a click event: The updated code attempts to determine if the internet connection is active. If the connection is off, the 'link' on the page will be disabled (non-click ...

The data in my AngularJS model will only refresh when the button is clicked twice

I am encountering an issue with a select list box and a button in my code. The aim is to filter the model displayed in the select list box based on the selectId received from clicking the button. The problem arises when the model updates only after clicki ...

Challenges in verifying user identities and maintaining session continuity in passport.js/Node.js

Currently, I am in the process of setting up passport for authentication on my node.js web application. However, I am encountering some difficulties with properly storing session data. Right now, it seems like the session data is not being stored at all. ...

Modify the colors of the chartist fill and stroke using JavaScript

Struggling to dynamically set colors in a chartist graph using JavaScript. How can custom colors be applied through JS? The attempted method below is not successfully changing the color for the showArea in the chartist graph. <!doctype html> <htm ...

How can I display color without using Winston's color formatter in text?

Currently, I am in the process of developing a logging module using winston as the selected logging framework. It offers the convenience of specifying colors, which is particularly appealing when utilizing the Console transport. However, if I were to defin ...

Is there a way to efficiently retrieve multiple values from an array and update data in a specific column using matching IDs?

In my Event Scheduler spreadsheet, I am looking for a way to efficiently manage adding or removing employees from the query table in column A. Currently, I have a dropdown list in each row to select names and a script that can only replace one name at a ...

Press the Enter key to generate a new table row

I have been dynamically creating an HTML table. Each row contains two columns created through a recursive call. Currently, a new row is generated by clicking on the second cell, but I want to switch this action to the "Enter" key press. Although my code su ...

Transform ISO-8859-1 encoding into UTF-8

Recently, I encountered an issue while sending a HTTP request using jQuery's ajax. The server, unfortunately, returns the response in ISO-8859-1 format while my page is set to UTF-8. This discrepancy causes some characters to become unreadable. How ...

modify the URL records within the GetJson function

My current address is "http://localhost:8000/index", and when I execute the following jQuery code: $.getJSON("1",function(data) { .....code }); It redirects to "http://localhost:8000/index/1". This works fine for now. ...

Attempting to move elements into an array for storage in the local storage

Is there a way to properly add elements to an array and store it in localstorage? Here's the code snippet I've been working with: const handleSelectLayouts = (layout) => { const layoutsArray = []; layoutsArray.includes(layout) ...