"Storing user information during a session in Node.js with Express and Socket.io

I am currently testing out this code snippet that I found online:

var io = require('socket.io'),
express = require('express'),
app = express(),
server = require('http').createServer(app),
connect = require('express/node_modules/connect');

var RedisStore = require("connect-redis")(express);
var sessionStore = new RedisStore()

var sessionSecret = 'sexret';
var sessionKey = 'sexpress.sid';
var sioCookieParser = express.cookieParser(sessionSecret);

app.configure(function() {
   app.use(connect.cookieParser());
   app.use(connect.session({ store: sessionStore, secret: sessionSecret, key: sessionKey }));
   app.use(express.static(__dirname + '/public'));
});

var sio = io.listen(server);

sio.set('authorization', function(data, accept) {
   sioCookieParser(data, {}, function(err) {
      if (err) {
        accept(err, false);
      } else {
        sessionStore.get(data.signedCookies[sessionKey], function(err, session) {
            if (err || !session) {
                accept('Session error', false);
            } else {
                // Trying to update data in the session

                if (session.yyy) {
                    session.yyy += 1;
                } else {
                    session.yyy = 0;
                }

                console.log("%j", session);

                // Data is not updating as expected

                data.session = session;
                data.sessionId = data.signedCookies[sessionKey];
                accept(null, true);
            }
        });
      }
  });
});

server.listen(1337);

I attempted another approach which didn't seem to work either:

sessionStore.get(data.signedCookies[sessionKey], function(err, session) {
  if (err || !session) {
    accept('Session error', false);
  } else {

    if (session.yyy) {
        session.yyy += 1;
    } else {
        session.yyy = 0;
    }

    console.log("%j", session);

    sessionStore.set(data.signedCookies[sessionKey], session, function(err, session) {

       data.session = session;
       data.sessionId = data.signedCookies[sessionKey];
       accept(null, true);

    });
  }

How can I successfully update data in the session?

Answer №1

It appears that the correct spelling should be sessionID instead of sessionId, as pointed out by Morgan in this useful response:

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

Is there a way to go about installing node_modules?

After running the npm i command to install node_modules in my vue.js project, I encountered the following error message: npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/@fds%2flima-ticket-validator - Not found npm ERR ...

Unable to initiate the server generated by the express.js generator

Currently, I am trying to set up an Express.js server using their generator. Following the documentation, I was able to successfully create the basic structure. However, when attempting to run the prescribed command (SET DEBUG=transcriptverificationserver: ...

Error message: Unable to locate the module '/node_modules/node-gyp/bin/node-gyp.js' on node-gyp

Why is node-gyp looking for node-gyp.js in an absolute path, when the actual installation directory of node-gyp is /usr/bin/node-gyp? If I run find /usr -name node-gyp.js the output shows /usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js / ...

Scouring the web with Cheerio to extract various information from Twitter

Just starting out with Web Scraping, using Axios to fetch the URL and Cheerio to access the data. Trying to scrape my Twitter account for the number of followers by inspecting the element holding that info, but not getting any results. Attempting to exec ...

Having trouble with installing npm packages? The node-gyp has encountered an end of line error while scanning the common.gypi

As I try to fetch dependencies for my React app using npm i, I encounter the following error: gyp info spawn args 'build', npm ERR! gyp info spawn args '-Goutput_dir=.' npm ERR! gyp info spawn args ] npm ERR! Traceback (most recent ...

Is Nuxt's FingerprintJS Module the Ultimate Server and Client Solution?

I am currently using fingerprintJS in my NuxtJS+Firebase project VuexStore. When I call the function on the client side, I can retrieve the Visitor ID. However, I am encountering issues when trying to use it on the server side, such as in nuxtServerInit. ...

Eliminating redundant JSON records upon fetching fresh data

I have a list containing duplicate entries: var myList = [ { "id": 1, name:"John Doe", age:30 }, { "id": 2, name:"Jane Smith", age:25 }, { "id": 3, name:"John Doe", age:30 }, { &qu ...

Unable to deploy Firebase functions following the addition of an NPM package

Scenario: I recently tried integrating Taiko into my Firebase web application, similar to Puppeteer. It's worth mentioning that Taiko downloads Chromium for its operations. Challenge: Ever since then, none of my functions are deploying successfully. ...

Crossrider: A Guide to Gathering Posts Using Node.js and PHP

Can you guide me on how to fetch a crossrider post using node js or php? Below is the post example: appAPI.ready(function($) { // Sending data with a JSON object appAPI.request.post({ url: 'http://example.com', // Data to send post ...

Guide to using AES-256-CBC encryption in Node.js and decrypting with OpenSSL on a Linux system

Question: Hello there, I am currently facing an issue with decrypting my encoded base64 using a specific command. Here is the command that I am trying to use: echo "base64key" | (openssl enc -AES-256-cbc -d -a -pass "pass:test" -pbkdf2 ...

NodeJS's pending ajax post using SailsJS

I'm experiencing an issue with processing AJAX data in my sailsJS app. The ajax post data always stays in the pending state, here is the code from my view: <script type="text/javascript"> $('#submit').click(function(){ $.ajax ...

The ins and outs of req and res objects in Node.js

Can you please provide information on the various properties and methods of response and request objects that are available in Node.js? For example, we often come across properties like request.url, or methods such as res.end and res.write. I would like ...

Why won't JavaScript functions within the same file recognize each other?

So I have multiple functions defined in scriptA.js: exports.performAction = async (a, b, c) => { return Promise.all(a.map(item => performAnotherAction(item, b, c) ) ) } exports.performAnotherAction = async (item, b, c) => { console.log(`$ ...

Storing website information efficiently with Node.js

I am new to Node.js and grappling with some concepts. Previously, I utilized apache and the .htaccess file for caching data. For example: ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" ...

npm: What could be the reason behind considering the version "0.1" as invalid?

To avoid an error with npm, I had to update the version of my npm app from 0.1 to 0.0.1. $ npm install npm ERR! install Couldn't read dependencies npm ERR! Error: invalid version: 0.1 npm ERR! at validVersion (/usr/local/Cellar/node/0.10.5/lib/no ...

What is the best way to retrieve data from a fetch request within a GET function?

It seems like a simple issue, but I'm struggling to retrieve information from my "body" when utilizing the get method. I've experimented with various approaches to extract the data, but nothing seems to work. Any guidance would be greatly appreci ...

Is it possible to generate a basic HTML page using Express JS without utilizing Ejs or any other templating engine

I have a basic HTML file with a Bootstrap form, along with a simple API coded within. In my server.js file, I've specified that when I request /about, it should redirect me to the about.html page. However, instead of redirecting, I'm encountering ...

Tips for getting involved in the Mojito repository on Github for javascript development

Looking for guidance on studying, understanding, and debugging code? I have a good grasp of javascript but unsure where to begin. I am familiar with Github and Mojito, but struggling to contribute to the platform. Any tips on how to get started with Moji ...

Is there a way to reduce the size or simplify the data in similar JSON objects using Node.js and NPM packages?

Is it possible to serialize objects of the type "ANY_TYPE" using standard Node tools.js or NPM modules? There may be multiple objects with this property. Original Json - https://pastebin.com/NL7A8amD Serialized Json - https://pastebin.com/AScG7g1R Thank ...

Simple request results in an error

I have been experimenting with the Electrolyte dependency injection library, but I am encountering an error even when trying a simple script that requires it. I haven't come across any discussions or problems similar to mine in relation to this issue ...