Is it possible to maintain variables across a session with numerous users when utilizing socket.io?

My code structure is designed as follows:

//Route Handler that triggers when a user 'creates a session'
app.post('/route', async (req, res) => {

    let var1 = [];
    let var2 = [];

    io.on('connection', (socket) => {

        //Utilizing var1 and var2 here

        socket.on('event', () => {
            // Utilizing var1 and var2 here
        });


    });


});

While my code operates effectively during one ongoing session, introducing a second user accessing the route alters the variables for active sessions leading to undesirable outcomes.

Instead of instantiating the variables upon each connection, I aim to have them set up with every occurrence of the 'sessionMade' event. Placing the variables within a socket method restricts their use for other socket.on methods.

I am seeking a solution where all sockets and global variables are contained within one session. Any assistance provided would be greatly valued. Thank you.

Answer №1

Ensure to utilize express-session for your application

const app = express()
const session = require('express-session');
const options = {
    name: 'foo',
    store: this.store,
    secret: 'bar', 
    saveUninitialized: true, 
    resave: false,
    rolling: true 
};

const middleware = session(options);
app.use(middleware)

In routes.js or in any handler file dedicated to a specific route:

handler(req, res, next) {
     req.session.someField = 'foo';
     req.session.save();
}

To learn more about express-session, visit here

If you prefer using an external session storage option, consider utilizing redis. Explore this useful tutorial on using Redis for session management in Node.js here

Answer №2

Is there a way to make them accessible globally?

let globalVar1 = [];
let globalVar2 = [];
//Code that runs when a session is created
app.post('/route', async (req, res) => {   
    io.on('connection', (socket) => {

        //Access globalVar1 and globalVar2 here

        socket.on('event', () => {
            // Access globalVar1 and globalVar2 here
        });
    });   
});

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

Heroku App push was unsuccessful due to compilation failure of the Node.js application

I made sure to include node_modules in .gitignore so that's not causing any issues! Does anyone have a solution for these errors? I've specified versions for both in the engines section. https://i.stack.imgur.com/tMDOd.png Here is the code : ...

Having trouble getting the npm package with @emotion/react and vite to function properly

Encountering an issue with the npm package dependencies after publishing, specifically with @emotion/react. This problem arose while using vite for packaging. Upon installing the package in another project, the css property appears as css="[object Ob ...

From javascript to utilizing ajax calls to interact with php scripts,

I am currently working on a page called edit.php where I need to pass a JavaScript variable to a modal window containing PHP in order to execute a query and retrieve data. Unfortunately, my experience with Ajax is limited and I haven't been able to fi ...

Code snippet for fetching JavaScript file using Angular's caching mechanism

Currently in my project, I am utilizing $.getScript to dynamically load specific sections of code. Here's a snippet of how it looks: var mainJs = "/main.js"; $.getScript( mainJs ) .then(function () { console.log("main.js loaded"); }); ...

Updating application state using information received from backend express server

I'm new to development and seeking some advice. I'm working on pulling data from an external API through my backend, which successfully displays the response in the console/backend. However, when I try to use that data on the frontend by modifyin ...

Ways to dynamically update the value of an object property within reactJS state

In the scenario where a component holds state like so: this.state = { enabled: { one: false, two: false, three: false } } What is the proper way to utilize this.setState() in order to set the value of a dynamic property? An attempt such ...

What is the best way to trigger an email from NodeMailer only upon confirmation of payment?

After confirming the payment and verifying it, I have set up NodeMailer to send an email to a specific email address obtained from req.body.email. However, I am encountering an error where the payment is processed without the email being sent. We are util ...

Encountering issues when implementing react-router with the client-side library

After following the author's suggestion, I've successfully loaded the client-side library. The recommended method is to simply drop a <script> tag in your page and use the UMD/global build hosted on cdnjs. I have ensured that ReactRouter i ...

Challenge encountered while creating a child tag that can be assigned to multiple parent tags

I have an xml format like the one provided. <xml> <parent id="0"> <child type="name"> </child> <child type="age"> </child> </parent> <parent id="1"> <ch ...

Calculate the sum of hours worked in a day using pure JavaScript, no external libraries required

Hello, I'm new to this website and please excuse me if my English is not perfect, I am trying my best to communicate :) I have been working on a page that calculates the total hours worked in a day and this is what I have achieved so far until 15/06 ...

Issue with jQuery selector not updating when variable changes

'I am attempting to create a functionality where a function is triggered upon clicking the "hit" class, but only when the correct parent "box" id is selected. var currentSelection = 1; $('#box-' + currentSelection + ' .hit'). ...

Tips for choosing all elements in a form that have a specific class assigned

I am attempting to target all fields in a form with a specific class name and then select all the remaining fields. This is my form: <form style="margin:20px 0" id="myform_2"> <p> Query Name : <input i ...

Encountered a Node Express Post 500 error (Internal Server Error) triggered by jquery-3.4.1.min.js

Recently, I've been immersed in developing a node js/express js application for quite some time. Most of my get's and post's are functioning properly when triggered from jquery $ajax calls. However, there seems to be an issue with one speci ...

:Incorporating active hyperlinks through javascript

Hey there, I've encountered a little conundrum. I have a header.php file that contains all the header information - navigation and logo. It's super convenient because I can include this file on all my pages where needed, making editing a breeze. ...

Include token in src tag requests Angular version 8

In the process of developing a website, I have encountered a challenge. I am creating a platform where users can access another website I am currently working on after they log in. Once authorized, users receive a JWT token which is sent in the header with ...

Identify specific elements using CSS to easily target them with JavaScript later on

Currently, I am utilizing CSS selectors to target specific elements and now I want to be able to identify those elements using javascript. My approach involves setting the color of these elements in css and then retrieving them based on their color. Howeve ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

Error message encountered in AngularJS when trying to send Fullcalendar: TypeError - Cannot access property '__id' of an undefined object

Recently, I integrated angular-ui-calendar into my website. Within the controller, I implemented the following: define(['underscore'], function (_) { "use strict"; var SearchController = function ($scope, $location, OrdersService, U ...

Parent window login portal

I have just started learning how to program web applications, so I am not familiar with all the technical terms yet. I want to create a login window that behaves like this: When a user clicks on the Login button, a window should pop up on the same page t ...

What is the best way to determine the range in which the value falls?

Currently, I am working on validating whether a User has the required karma (reputation) to perform certain actions, such as placing a bid on an item. The karma value falls within the interval [-25; 100]. Additionally, it is noted that as a user accumulate ...