Second user session takes precedence over first user session in Express-session

Here we have a get request that passes the user to the view.

app.get('/blog/:id', function(req, res) {
  // Define the page
  res.render('blog', {
    user: req.user,
});
}); 

In this textarea, all users on this page should have their names stored.

<textarea readonly id="usersInRoom" placeholder="<%= user.username %>"></textarea>

This code successfully sets the correct username as the placeholder. However, if another user visits the same page at the same time, only their username will be displayed. How can we save the first user's username so that the second user sees both usernames concatenated in the placeholder? Note that data stored by one user is not accessible to another user visiting the same page.

Answer â„–1

In the situation where SignalR is being utilized, one option is to broadcast the current list of users to each connection and update the view, similar to how it's done in the sample chat application.

If regular ajax server polling is being used instead, a client method can be set on an interval to retrieve a list of current page users from a database store. Due to http's lack of state, users who have not posted recently would need to be removed from the list.

Client code:

setInterval(checkServer,5000);
function checkServer(){
    //ajax call to the server here 
    //to fetch the user list
    ...
    success:function(result){
       $('#usersInRoom').val(result);
    }
}

Server code (assuming all current page users are stored in a table with a LastModified field):

CurrentPageUser class (saved in DbContext as CurrentPageUsers table):

public class CurrentPageUser{
   public int Id {get;set;}
   public DateTime LastModified {get;set;}
   public string Name {get;set;}
}

Controller method:

public string GetCurrentUsers(int selfid){
    using (var db=new DbContext()){
       var now=DateTime.Now;
       //update requesting user so others can see them
       db.CurrentPageUsers.Find(selfid).LastModified=now;
       db.SaveChanges();
       DateTime timelimit = now.AddMinutes-5);
       return string.Join(", ",
         db.CurrentPageUsers.Where(u=>
            u.LastModified<timelimit).Select(u=>u.Name).ToList());
    }
}

It's important to note that while the SignalR implementation offers better performance and is simpler to implement on the server side without needing a database table for storing current page users, it was specifically designed for this type of scenario.

Answer â„–2

After much troubleshooting, I finally figured out the issue. It turns out that my use of express-sessions was causing my login sessions to persist. This led to a scenario where the first user's session data was being replaced by a second user who logged in while the first user was still online. As a result, the second user ended up being logged into the system on two different browsers simultaneously.

Even though I tried accessing the system from different browsers and devices, it wasn't until I realized that the node app was hosted locally at localhost that the problem became clear. Once I uploaded the app to Heroku and accessed it from there, the issue with user sessions getting overwritten was resolved.

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

Navigating to and Revealing a Division by Clicking

Check out this code snippet: <a onclick="$('a[href=\'#tab-customtab\']').trigger('click');">Enquire Now</a> <div id="tab-customtab"></div> This piece of code triggers the opening of the #ta ...

jQuery validation on select box change event

A project I'm working on involves designing a show/hide feature for a div select box using select2 and validating it using the jQuery validation plugin. Everything seems to be working fine, except for one issue I've encountered. When I select an ...

Vuetify alters the text color of the <vs-button> element

Outline of the Issue Upon installing vuetify, the text color of my <vs-button> has changed from white to black. Despite trying to adjust the color in the vuetify theme, I am unable to change it back. I have also created a custom filter rule using po ...

Is it possible to disregard any spaces within the content of an <option> element?

In my current project, I am facing an issue where a Django server is sending JSON data to a template with Vue.js running on it. The problem arises from the fact that some values in the JSON data have trailing spaces, causing complications. I am looking for ...

Dealing with Errors in Promises: A guide

Recently I started learning about Promises and how to handle errors using promise Catch blocks. I have a question - is there a way to streamline error handling by using only one catch block instead of two in my code? I would appreciate any help or sugges ...

Guide to programmatically configuring meta title, description, and image in a Vue.js project with the help of Vue Unhead and Vue Meta

I'm currently developing a Vue.js project where I need to dynamically set the meta title, description, and image based on data fetched from an API. To handle the meta tags, I am utilizing Vue Vue Unhead along with Vue Meta. Below is a snippet of the r ...

Why doesn't WebStorm display TypeScript inspection errors in real-time?

I'm currently utilizing WebStorm 2017.2.4 in conjunction with Angular 4.3 - I am facing an issue where TypeScript errors are not being displayed: https://i.sstatic.net/pcLQX.png Query How can I enable real-time inspections to occur immediately? (I ...

Filtering an array within an array based on user input

I am currently facing a challenge in filtering the child elements of an array. I am puzzled on how to specifically target children elements. So far, my filter is only functioning at the top level. Array: options: [ {name: 'Ð’Ñ‹Ñ…Ð ...

Is there a method to ascertain the relative position of a point on a polygon?

Apologies in advance as I might have a hard time wording this question properly, so I'll start by explaining my objective. I'm currently working with JavaScript and Raphael. My goal is to save the position of a point in relation to the four cor ...

Lusca CSRF not functioning properly due to HTTP requests using outdated tokens

Implementing CSRF protection with lusca on my Express.js application has proven to be a bit tricky. Here is how I have it set up: this.app.use(lusca({ csrf: { cookie: {name: '_csrf'} }, hsts: { maxAge: 31536000, include ...

Discovering all class names following the same naming convention and storing them in an array through Javascript

Hey everyone, I could use some assistance with a coding challenge. I'm aiming to extract all class names from the DOM that share a common naming convention and store them in an array. For instance: <div class="userName_342">John</div> & ...

Using cannonjs and Three.js to connect a physics body with a visual mesh

I have written the code below to create two spheres using cannonjs with Three.js for rendering. var world, mass, body, shape, timeStep=1/60, camera, scene, renderer, geometry, material, mesh; initThree(); initCannon(); animate(); func ...

Unable to locate 'react' for mdl module

Currently working on my first website using react, following a tutorial available at this link I am attempting to install and utilize the material lite module, but encounter a compilation error when starting npm with the following message: Error: Module ...

My angles seem to be skewed, yet the movement is still functioning in my 2D, top-down game. What's causing

I am currently developing a 2D birds-eye view game in JavaScript without using any engine or library, mainly for the learning experience. I have successfully implemented character movement using WASD keys, where the character moves forwards (W) or backward ...

An error occurred during runtime due to a TypeError when trying to execute the 'setItem' function on 'Storage'. The error message indicates that 2 arguments are required for this function, but only 1 argument

Having an issue with the local storage not working and the screen showing up as white in the browser. 5 | const getFromLocalStorage = () => { 6 | if (typeof window !== undefined) { > 7 | const value = localStorage.getItem(& ...

Is there a way to set overflow-x to auto and overflow-y to visible simultaneously?

I'm facing a specific issue where I need to display overflow in a horizontal direction for scrolling, but not in the vertical direction. Perhaps an image can clarify this better. Is there a solution using CSS or JavaScript to achieve this? ...

Validation of Style

Is there a way to translate the following CSS code into JavaScript? Basically, I want it to apply the style rules after the onchange event. .appnitro input:required:valid, .appnitro textarea:required:valid { box-shadow: 0 0 5px #5cd053; border-c ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...

Obtain information through ajax using an asynchronous function

When fetching data in the first example using ajax with XMLHttpRequest, everything works smoothly. example 1 let req = new XMLHttpRequest(); req.open( "GET", "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-tempe ...

Struggling to determine the expense upon button activation - data remains stagnant

My coding project involves a basic ordering system where users can input an integer, click on an update button, and see the total cost displayed below. Despite my efforts, I've encountered issues with two different methods: Using plain JavaScript for ...