Express and socket.io do not allow the sharing of socket sessions

I've been struggling to pass session data from socket.io to express routes using express-socket.io-session. Despite saving the data on the socket's "connection" event, my express routes are not able to access the updated session variables. I have tried various configurations without success.

const path = require('path');

const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const session = require('express-session')({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
});
var sharedsession = require('express-socket.io-session');

app.use(session);

io.use(sharedsession(session, {
    autoSave: true
}))

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

    socket.handshake.session.data = ['connection']
    console.log(socket.handshake.session);

    // First
    socket.on('login', data => {
        socket.handshake.session.data.push('login');
        console.log(socket.handshake.session);
    });
})

// Second
app.get('/route', (req, res, next) => {
    console.log(req.session.data); // => undefined
})

app.get('/*', (req, res, next) => {
    res.sendFile(path.join(__dirname, 'index.html'));
})

server.listen(3000);

After numerous failed attempts to troubleshoot this issue, I have created a minimal example in a repository to showcase the problem: https://github.com/matt-mcdaniel/express-socket-test

Why am I unable to retrieve the saved data from my socket connection in my express routes?

Answer №1

One key aspect that may have been overlooked is the necessity of using the .save() method when assigning a value to session from socket io. The correct approach should involve incorporating the .save() method after setting the value, such as in this example: socket.handshake.session.data = ['connection']; socket.handshake.session.save();

By following this protocol, the operation should function as intended.

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

Can both a Node image and a Python image be run simultaneously within a single Dockerfile?

I am considering putting my logic and backend in python and the frontend in React/Typescript. However, I am unsure if it's feasible to have a single Dockerfile that incorporates both a python image and a node image. Should I pursue this approach or o ...

The functionality of `req.isAuthenticated()` is never true when using PassportJs with a combination of nodeJS and dynam

I am entering the world of web programming and tasked with creating an Instagram-like platform for my school. The frontend is built in ReactJS and now it's time to develop a server in nodeJS, utilizing passport for authentication and dynamoDb for data ...

What is the process for transforming an asynchronous method into a synchronous version?

I am currently working on creating a functionality similar to the core fs module's methods, where there is an Async method by default and a Sync method if requested like fs.readDir() and fs.readDirSync(). In my case, I have a method named fetchUrls w ...

Experiencing difficulties while attempting to send a put request to a MySQL database using Node.js

Encountering an issue when attempting to send a PUT request to update a row in a product table within MySQL using Node.js. Below is the code snippet: exports.updateProduct=(req,res)=>{ const productId=req.params.productId; const keys=Object.keys(req.bo ...

Selecting nested objects in MongoDb

One of the challenges I am facing is dealing with multiple nested objects and lists in my data structure, which looks something like this: { "_id": "5a76be26ca96e22f08af2a19", "testId": "123", "testName": "summerTest", "subjects": [ { "subject ...

Resetting passwords in Node.js using ldapjs without the need for the current password

Is there a way to reset an active directory password in Node.js without knowing the current password? Currently, I am using the following 2 libraries: https://www.npmjs.com/package/activedirectory The code snippet below works perfectly for resetting pas ...

Selectize Fails to Populate Options Using Ajax

ExpressJS is the platform I am using to develop a management dashboard for a community project. Right now, my main concern is integrating a modal that allows users to add new games to a database. Although I am able to fetch data remotely, I am facing diffi ...

Utilizing the power of Node.js clustering for secure HTTPS connections

Currently, I am utilizing the cluster npm for my Node.js application. var cluster = require('cluster'); var app = express.createServer({ key: fs.readFileSync('privatekey.pem'), cert: fs.readFileSync('certificate.pem&apos ...

Sequelize encountered an error: Unhandled promise rejection of type TypeError: Unable to access property '_pseudo of undefined'

After cloning this app from https://github.com/sequelize/express-example, I noticed that it is the official sequelize express example. However, upon attempting to run it, I encountered the following error: Unhandled rejection TypeError: Cannot read proper ...

Implement a cron job in Node.js to automatically trigger an Express route on a weekly basis

I need to run tests on a certain page every week by creating a cron job that will access my express route at regular intervals. Currently, I have set up a cron job to run every 2 minutes as a test: //schedule job every 2 minutes schedule.scheduleJob("* /2 ...

Dealing with missing data in web scraping efforts

Looking to scrape the specified page, however encountering empty fields within the ".trans-section" node. The '.trans-section' node contains both 'title' and 'description'. In certain instances, the title exists but the descri ...

Error message: "Please ensure that you have installed with the -g flag"

I am facing issues with installing Grunt on my computer. Despite following several tutorials and the official installation guide, I am unable to get it up and running. The command line interface installs successfully using the following command: sudo npm ...

Guide on utilizing NodeJS for the reading of extensive UTF-8 encoded text files

When it comes to using NodeJS to read utf-8 encoded text files, there are plenty of answers out there. However, the real question arises when dealing with large files that exceed memory capabilities, such as a 64GB file. Imagine having a massive 64GB JSON ...

Having trouble retrieving a random document from a MongoDB collection?

I'm currently developing a word game and facing the challenge of displaying a random wordpair from my collection on page load. Utilizing Express, I've modified my code based on a helpful tutorial. With a successful GET request rendering my page ...

Sending Node.js variables to HTML with the help of Ajax

I am attempting to pass JSON results from Python to HTML using AJAX in Node.js. My objective is to collect client-side inputs, send them via AJAX to Node.js when a submit button is clicked, and then have the /data middleware execute a Python script that i ...

Harness the power of Angular 2 on standard shared hosting services

Starting with AngularJS 2: Installed NodeJS Downloaded the initial project Ran it on Node Everything works perfectly! But now, how can I run it in a production environment on shared hosting (without Node and not on a VPS)? How can I open it in a browse ...

What is the process for configuring electron-builder.js within the directory of my project?

image of my project's structure In my current project, I am combining electron and react to create an application. All the necessary settings for execution are specified in the package.json file. The code I have written is displaying as expected. H ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

Tips for selecting a checkbox with Puppeteer

I've implemented the code in this way: await page.$eval('input[name=name_check]', check => { check.checked = true; }); This code is intended for multiple checkboxes. However, I need it to work for a single checkbox only. Is there a way ...

obtain a Javascript variable within a Jade template by using inline code

script. var hide_section = 'block'; .title(style='display:#{hide_section}') I received an undefined value, any thoughts on why? Could it be because #{hide_section} is trying to access a variable from the back-end, such as the cont ...