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

The datatable fails to render after executing a function in AngularJS

When I load the page without calling a function, the data is displayed in a datatable perfectly fine. However, if I try to generate the datatable after calling a function, it does not work. HTML: <div class="widget-body no-padding"> ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

AngularFire Google OAuth failing to retrieve the user's email address

I am trying to retrieve the email address from Google OAuth using AngularFire, but the popup is not requesting permission for the email. This code snippet is from the Firebase Google authentication documentation var ref = new Firebase("https://<your-f ...

Having trouble with npm and unable to find a solution that works. Any suggestions on how to fix it?

I've been working on a JavaScript project that requires me to import a library, but I keep running into errors with npm every time I try to use it. Here is the error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

When trying to use bootstrap modal buttons, they do not trigger with just a single click when

In my Angular code, I have implemented validation logic for when $locationChangeStart is fired. When this event occurs, I need to call event.preventDefault() to stop it and display a Bootstrap modal. However, I am encountering an issue where I have to clic ...

The execution of the Javascript function is not being carried out

Why is alert("Test1") being executed, but alert("Test2") is not running? P.S. I'm currently not utilizing JSON data. <script> $(document).ready(function() { var param = 10; $.getJSON( 'modules/mod_sche ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

What could be causing ExpressJS to show an empty array on the initial GET request, only to display the data from the previous request on subsequent GET requests?

I have been working on a project involving Express and MongoDB, and I've successfully created an API server that can perform CRUD operations on a single post. However, I've encountered a challenge when trying to retrieve all documents from MongoD ...

Unable to identify collision in JavaScript's 3D environment

I'm currently using three.js to develop a simulation of Brownian Motion, but I've hit a roadblock when it comes to getting the tiny molecules to collide with each other. This is the snippet I have at the moment: function intersects(sphere, other ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

Mobile device experiences shader malfunction

On my laptop, this shader works perfectly fine. However, I'm facing issues on mobile devices and suspect that it might be related to precision settings. Here is the error message I'm encountering: THREE.WebGLProgram: shader error - 0 35715 fals ...

Troubleshooting issues with Angular's scope functionality

Here is my controller: angular.module('app', []) .controller('ctrl', ['$scope', function ($scope) { $scope.daysPerMonth = new Date(year, month).getDate(); }] ); This is the corresponding html: <div ng-app> <h1&g ...

A guide to building a versatile dropdown component with Material UI or MUI in a React application

Is there a way to create a reusable dropdown component using Material UI or MUI in React? ...

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

Submitting data with AJAX to a NodeJS server

I have experience creating basic web applications where data is transmitted via HTTP parameters. However, I am currently attempting to send data from the client-side that includes an array (a list of ingredients for a recipe) and potentially a user-uploade ...

The position of the carousel items changes unpredictably

My jQuery carousel consists of 6 individual items scrolling horizontally. Although the scroll function is working correctly, I have noticed that 2 of the items are randomly changing their vertical position by approximately 15 pixels. Upon reviewing the HT ...

What steps can I take to display a "Sign in with Paypal" button on a React App?

Disclaimer: I am relatively new to React and have only been dabbling with it for a day. I came across this tutorial source code that is designed for logging in with Google. https://github.com/The-Tech-Tutor/spring-react-login My goal is to integrate a "L ...

Struggling to animate the selector of a nested div in Jquery?

Despite trying numerous variations, I am struggling to identify the correct selector of a nested div. The goal is to animate this particular div, but since no animations are taking place, I suspect that I have not selected the right element. Here is the a ...

The function '$("#elementId").change()' is not functioning correctly, while '$(document).on("change" "elementId")' is operating effectively

Recently, I have encountered an issue on my web pages where the $("#elementId").change() function does not work for elements on a JSP page. However, using $(document).on("change" "elementId") seems to work. It appears that the page's document is being ...

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...