Unable to assign a value to the property of the socket.io handshake object

I am attempting to include a custom attribute in a socket.io handshake and transfer it to the socket object upon each connection.

Below is a basic outline of my approach:

var app = express();
var http = require("http").Server(app);

var io = require("socket.io")(http);

io.set('authorization', function(data, callback){
  data.foo = 'bar';
  callback(null, true);
});

The code above should allow me to access a foo property on the socket.handshake object. However, when I try the following:

io.sockets.on('connection', function (socket) {
    console.log(socket.handshake.foo); //This should output bar
});

I receive an undefined value.

Answer №1

With the latest version of Socket.IO 1.0, the traditional handshake object has been replaced by socket.request.

Here's how you can implement this:

io.sockets.on('connection', function (socket) {
    console.log(socket.request.foo);
});

For more detailed information about the changes between versions 0.9 and 1.0, click here.

It's important to note that many online resources and tutorials still reference Socket.IO 0.9, so the content on this page can be quite valuable in transitioning to the new version ;)

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

Encountering a 404 error while attempting to use the HTTP PUT method with Node Express

Update: Disregard my previous message - I made a small error in the Angular service. My apologies. I'm expanding my knowledge of backend development by creating a basic CMS using Angular, Node, Express, and PostgreSql. I've managed to implement ...

Issue with installing chromedriver and selenium-driver on Windows 7 using NPM arise

I have a relatively basic package.json file with some development dependencies included. Here is what it looks like: "devDependencies": { "cssnano": "3.3.2", "cucumber": "0.9.2", "diff": "2.2.0", "grunt": "0.4.5", "jit-grunt": "0.9.1", " ...

Delete with Express Router

I have created a basic "Grocery List" web application using the MERN stack (Mongo, Express, React, Node). However, I am facing an issue where my DELETE REST command does not execute unless I refresh the page. Here is the code for my event handler and the b ...

Kindly include a @Pipe/@Directive/@Component annotation within an Angular 6 project

Encountering an issue in Angular6 where I am receiving the error message Please add a @Pipe/@Directive/@Component annotation Using angular CLI version: 6.1.4 angular version: 6.1.3 Node: 10.9.0 NPM: 6.2.0 After running ng serve in Terminal, the applicati ...

Retrieving the initial element from the $resource.query() function in AngularJS

I am encountering an issue with the $resource.query() method. My goal is to retrieve the first element from it, but unfortunately, I am having trouble achieving this. Surprisingly, the selection controllers are able to return the collection without any hic ...

Running `server.js` will function properly, however executing `npm start` will not yield the

I encountered an issue when attempting to run a node app using npm. If I use the command node server.js, it runs successfully, but when I try npm start, I receive the following error: npm ERR! file bash npm ERR! path bash npm ERR! code ELIFECYCLE npm ERR! ...

What is the best method for enabling communication between two users when the identification numbers created by socketIO are automatically generated?

Hey there, hope you're doing well. I've been pondering a question that has left me stumped. I recently came across a course that explained how to send a message to a specific user using socketIO.js by utilizing the `to()` method and passing the ...

When NestJS injects an ObjectionJS model, it encounters an exception

Whenever I attempt to inject an Objection.js model into a NestJs service: constructor(@Inject('UserModel') private readonly modelClass: ModelClass<UserModel>) {} I encounter a compile time error stating Maximum call stack size exceeded. I ...

Understanding the complexity of npm dependencies

I'm currently delving into the intricacies of npm dependencies and trying to understand why certain versions are not showing up as expected. In a nutshell, my main question is: given a scenario where a package is invoked multiple times with differing ...

Is there a yarn equivalent for perpetually running nodes?

Currently, I run the command yarn run dev-server using the screen. I am searching for an alternative method similar to: forever start app.js Specifically for the yarn run dev-server command. The definition of dev-server in package.json is equal to "dev- ...

Executing multiple requests simultaneously with varying identifiers following a waiting period

I am looking to send a GET request using the user_id key retrieved from the userData object. This is how the request should be structured: Let's assume we have userData defined as follows: var userData = [ { id: 1, user_id: ...

The issue of undefined req.user in NodeJS Express Passport

Testing authentication in a small app using express+passport without sessions. User must provide username and password for every action. After authorization (passport.authenticate()), request.user is undefined in the next middleware, even though passport&a ...

Node(Meteor) experiencing a memory leak due to setTimeout

I have encountered an unusual memory leak associated with the use of setTimeout. Every 15 seconds, I execute the following code using an async function that returns an array of promises (Promise.all). The code is supposed to run again 15 seconds after all ...

Display the header on every single page using puppeteer

            Whenever I enable displayHeaderFooter, the header does not display. It only works if I add margin to @page in my CSS, but this causes the page height to increase by the margin value and content to overflow beyond the page boundaries. Is ...

What steps can I take to catch the 413 error triggered by Express if a request's body exceeds the specified size limit?

When a user sends a request to my API with a payload that exceeds the set limit, I want to catch the error thrown by the server and handle it on my own so that I can provide a more detailed JSON response to the client. Currently, I am utilizing the Expres ...

Having trouble storing data in a MYSQL database with NodeJS and ReactJS

When trying to submit the form, a "Query Error" popup appears and data is not being saved in the database. API router.post("/add_customer", (req, res) => { const sql = `INSERT INTO customer (name, mobile, email, address, state, city, policytype, insu ...

What is preventing my AJAX response from being ETag-cached without the If-None-Match header?

Below is the AJAX function I am using: function ajax(url, data) { return new Promise((resolve, reject) => { $.ajax({ url: "https://xxx", data: data, method: 'POST', timeout: 50000, ...

Utilize client-side script in nodejs to share module functionalities

I created a function within the user controller module to verify if a user is logged in on the site: exports.isLoggedIn = function(req, res, next) { if (req.user) { return true; } else { return false; } }; I'm unsure of h ...

Guide to redirecting data from an external POST request to a customer through a GET request

Within my Express application, I am currently dealing with both incoming POST requests containing a payload from an external source and GET requests sent by my client: router.post('/liveReleaseStore', (req, res) => { let data = req.body.m ...

Node.js tutorials failing to run on Windows 7 platform

After downloading node.js version 0.6.6 from http://nodejs.org/#download and running it on my Windows 7 32-bit system, I encountered some issues. Despite following tutorials online, I couldn't get node.js to work properly. Although the .js file would ...