The re-assignment of `req.session.variable` in Express-session does not carry over between two different routes

I am currently working on a basic app that allows logged in users to search and book train journeys using Express, MongoDB, Mongoose, and Express-session. The selected journeys are temporarily stored in the req.session.order variable (which I believe is global across all routes). Once the user confirms the booking, the selected journeys are saved as sub-documents of the user in the database. The issue I'm facing is that even after confirmation, when returning to the home page, the req.session.order array still contains previously booked journeys.

After reviewing the code below, it seems that the req.session.order array is properly cleared at the end of the /confirm route instruction. However, upon navigating back to the home page, the console continues to display previously pushed journey ids.

I suspect there may be an issue with how express-session is being utilized. Any assistance you can provide will be greatly appreciated.

// (req.session.order is initialized to [] in signin/signup routes before redirecting to the home page)

/* GET confirmation page. */
router.get('/order', async function(req, res, next) {
  var bookedJourney = await journeyModel.findOne({ _id: req.query.id });
  **req.session.order.push(bookedJourney);**
  res.render('confirmation', {order: req.session.order, reformatTime: reformatTime, reformatDate: reformatDate});
});

/* POST add selected journeys to trip list */
router.post('/confirm', async function(req, res, next) {
  var currentUser = await userModel.findOne({ email: req.session.user.email });
  req.session.order.forEach((order) => {
    currentUser.journey.push(order._id);
  });
  await currentUser.save();
  **req.session.order = []; // This successfully clears the array as expected**
  console.log(req.session.order);
});

In the HTML, when clicking on the confirm button, a modal is launched with a button leading back to the home page:

/* GET home page. */
router.get('/home', function(req, res, next) {
  **console.log(req.session.order); // Not sure why req.session.order here still has the bookedJourney id, it should be empty []**
  if (!req.session.user) {
    res.redirect("/");
  } else {
    console.log(req.session.order); // Ditto
    res.render('home', { user: req.session.user });
  }
});

Answer №1

In order for changes to session objects to take effect, it is important to save them by using req.session.save(). When sessions are stored in the default memory store, you might be able to modify certain aspects of the session (such as modifying an embedded object like an array) without issues. However, when transitioning to a more robust production-ready store, these types of modifications may no longer function correctly.

After making any changes to the session, remember to execute req.session.save().

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

"Trouble with Angular JS foreach loop: only the final item in the array

Struggling to loop through each item object in a JSON data set and evaluate its value using angular.forEach(). However, only the last item is being returned, making it impossible to perform any meaningful evaluation. Oddly enough, when using console.log(), ...

I am having trouble getting two similar Javascript codes to function simultaneously

Using a common JavaScript code, I am able to display a div when a certain value is selected. http://jsfiddle.net/FvMYz/ $(function() { $('#craft').change(function(){ $('.colors').hide(); $('#' + $(this ...

Generate unique identifiers to rotate images dynamically on the webpage

My goal is to rotate every image on a page, and while this works with a single image, it only rotates the first one since each ID needs to be unique. I need to find a way to dynamically increment the IDs as they are encountered on the page. Below is what I ...

Issue with Angular 17 button click functionality not functioning as expected

Having trouble with a button that should trigger the function fun(). Here's the code snippet I'm using. In my TS file: fun(): void { this.test = 'You are my hero!'; alert('hello') } Here is the respective HTML: &l ...

Finding alternative solutions without using the find() method when working with Angular

How can I use an equivalent to find(".class") in AngularJS? I came across this solution: //find('.classname'), assumes you already have the starting elem to search from angular.element(elem.querySelector('.classname')) I attempted to ...

Tips on storing information within a Vue instance

Seeking a simple solution, all I need is to save data retrieved after an AJAX post in the Vue instance's data. See below for my code: const VMList = new Vue({ el: '#MODAL_USER_DATA', data: { user: []//, //userAcc: [] }, met ...

NGINX Reverse Proxy Troubles with 502 Errors Occur on Certain Pages

Running on an Ubuntu server, my Node.js/Express application is behind an NGINX reverse proxy that directs traffic on port 80 (or 443 for SSL) to the application's port. Lately, I've encountered a strange issue where attempts to access / eventual ...

Encountering issues with app functionality following update to Ionic RC4 version

Since upgrading from Ionic rc3 to rc4, I've been facing difficulties running my app smoothly. The app compiles without any errors when I use ionic-app-scripts build --prod, but when I try to run it on my iPhone, all I get is a blank screen and an err ...

Retrieve the text from an ajax response that includes the <tag> element

I have created a simple piece of code to fetch news from an RSS page. Below is the code snippet: this.loadRecentNews = function loadRecentNews() { $.get("http://rss.nytimes.com/services/xml/rss/nyt/GlobalHome.xml", function (data) { ...

What methods does GitHub use to determine my login status?

I removed the localStorage storage, but it didn't make a difference. I'm curious - does GitHub store IP addresses of logged-in users in a database, or maybe in browser headers? ...

React components receive props as an empty array when they are being passed to the component

I am passing a state to a component as a prop in the following way: componentDidMount() { axios.get("path/to/data") .then(result => { this.setState({ receivedData: result.data, }); ...

Vue-router vulnerability allowing for DOM-based open redirects

I am currently working on a Vue application that was created using Vue-cli. Vue version: 2.6.11 vue-router version: 3.2.0 Link for Reproduction https://github.com/keyhangholami/dom-based-open-redirect Instructions to replicate To reproduce the i ...

button that decreases in size when clicked on

Currently, I am dealing with an element that functions as a button using a combination of Javascript and CSS. To better illustrate the issue, I will simplify the example by removing unnecessary details. The main problem lies in the fact that when this elem ...

Bootstrap modal experiencing technical difficulties

I am experiencing issues with my bootstrap modal. It seems to be malfunctioning, almost as if the CSS or JavaScript files are not being recognized. I have tried various solutions but have been unable to resolve the problem. I even attempted using the examp ...

Enhancing TypeScript type definitions for the Response.render() method in Express

Struggling with enhancing the type safety of my Express project by extending the Response.render function. import { Response } from "express"; import { Product } from "../models/Product.interface"; export interface ProductListResponse ...

Retaining previous values in Angular reactive form during the (change) event callback

Imagine having an Angular reactive form with an input field. The goal is to keep track of the old value whenever the input changes and display it somewhere on the page. Below is a code snippet that achieves this functionality: @Component({ selector: & ...

Using CDN to load the STLLoader in Three.js

After deciding to have some fun by creating an STL loader, I've hit a roadblock. Despite trying various solutions found online, I'm still facing issues, mainly due to CDN errors. Currently, I'm following the tutorial on the Three.js site and ...

What sets Import apart from require in TypeScript?

I've been grappling with the nuances between import and require when it comes to using classes/modules from other files. The confusion arises when I try to use require('./config.json') and it works, but import config from './config.json ...

The state in a functional component in React fails to update after the initial axios call

Issue : The value of "detectLanguageKey" only updates after selecting the language from the dropdown twice. Even after selecting an option from the dropdown for the first time, the detectLanguageKey remains empty and is only updated on the second selectio ...

I'm looking for a way to implement a jQuery-style initialization pattern using TypeScript - how can I

My library utilizes a jQuery-like initialization pattern, along with some specific requirements for the types it should accept and return: function JQueryInitializer ( selector /*: string | INSTANCE_OF_JQUERY*/ ) { if ( selector.__jquery ) return select ...