Exploring the use of cookies within Socket.IO and accessing them through devtools while utilizing Express-session

Why am I encountering difficulties accessing this particular cookie?https://i.sstatic.net/apdIS.png

Upon the user's logging in, the cookie is acquired and transmitted back to the Express server.

Despite these actions, when establishing a new websocket connection to the Socket.io server, this specific cookie fails to be transmitted. As a result, attempts were made to retrieve it using document.cookie. Unfortunately, these efforts proved futile due to the cookie being non-modifiable.

https://i.sstatic.net/TOrvb.png

Answer №1

This cookie is marked as HttpOnly, meaning it cannot be accessed by client-side Javascript.

In simpler terms: The server can view and change the cookie, while the client receives it and sends it back with every request without being able to see or modify its contents using Javascript.

Answer №2

The official website presented a solution that didn't quite work for my needs. express session middleware

const session = require("express-session");

io.use(wrap(session({ secret: "cats" })));

io.on("connection", (socket) => {
  const session = socket.request.session;
});

To work around the issue, I implemented the following logic:

Prior to establishing the websocket connection, request credentials from the express endpoint "/userCredentials"
and then utilize these credentials to establish the connection

Note: The code below has been removed due to extensive authentication processes.

CLIENT: 
...
useEffect(() => {
  (async() => {
    const pending_creds = await fetch("/userCredentials");
    const creds = pending_creds.json();
    
    const ws = io({auth: {creds}})
    
    setSocket(ws)
  })()
}, [])

...

SERVER:


...
app.get("/userCredentials", (req,res) => {
  const userSession = req.session.user;
  
  res.json(userSession)
})
...

io.use(socket, next){
  const creds = socket.handshake.auth.userSession;
  if(creds){
    next()
  } else {
    socket.disconnect()
  }
}

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

Uncaught ReferenceError: cliSystemConfigPackages has not been declared

When diving into Angular 2 programming, I encountered an error message and sought out a solution. After searching for answers, I came across this helpful response: Error: ReferenceError: cliSystemConfigPackages is not defined Unfortunately, none of the s ...

Just starting out with JS, curious if it's possible to transform these circles into diamonds instead

My goal is to transform this animated field of blinking circles into rectangles or diamonds, whichever is easier. Link: http://jsfiddle.net/Jksb5/1/ HTML <canvas id="pixie"></canvas> JS var WIDTH; var HEIGHT; var canvas; var con; var g; va ...

What is the procedure for eliminating a cookie with Javascript?

Is there a way to delete the cookie set by javascript:void(document.cookie=”PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;path=/; domain=.google.com”); The code below fails to do so. javascript:void(docum ...

I'm having trouble getting my bot command handler to function properly

When it comes to my command handler, the commands function properly. However, when I attempt to include arguments like $user-info @user instead of just $user-info, it returns an error stating that the command is invalid. Code //handler const prefix = &ap ...

The validation function in mongoose is malfunctioning

I am currently attempting to validate my document to ensure it contains a media URL and corresponding media type. I have implemented the following validator: mediaURL: { type: String, default: '' }, ...

The AngularJS framework is failing to disable the autocomplete feature for the input field with a password type

I have attempted to disable auto-complete for the password input, but it doesn't seem to be working. Below is a sample of my code: <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off"> <input type="password" id="passwor ...

The script fails to load when utilizing jquery/ajax

After the page loads, I am attempting to dynamically add a script into a div using ajax/jquery. This particular script is sourced from a CPM network and is responsible for loading a banner. However, when I try to load this script through ajax post-page lo ...

Redux - Refreshing the subtree state

How can I properly reset the subtree of a redux store without resetting the entire store? I want to target only the reducer subtree in question. Check out this example code: //initial state const initialState = { isFetching: false, error: '& ...

Assign the input to the cell that I have selected

Currently, I am in the process of constructing a user database in React-bootstrap Table. Each cell in the table contains ID, Name, Email, Comments, and two buttons for Delete and Edit. When the Edit button is clicked, I want to enable input tags for Name, ...

Uploading image files from React Native (Expo) to a Node server (Express)

Is there a way to efficiently upload an image file like png or jpeg from React Native using expo to a Node server with Express? As a newcomer to mobile UI development, I found the Expo documentation lacking in this area. I attempted to use multer (referen ...

What is the best way to create a case-insensitive search feature in Node.js?

I have implemented a search function that takes input from the client as Str. If it matches with content in a file, I send that response. For example, if I have text in a file labeled Lorem, and the client searches for lorem, it returns an empty array due ...

It appears that the functionality of RegExp.prototype.exec() is not functioning as expected

const fs = require('fs') const jsdocFinder = /\/\*\*\n(.+?)\*\//gs /** * Implementing a function to convert JSDocs into JSON format. * @function * @param {String[] | String} dirs The directory or directories of ...

Having trouble with shipit.js deployment: Error encountered - git checkout undefined

I have been using shipit.js to deploy my nodejs application on an Ubuntu 16.04 server successfully. However, I recently encountered the following error: ./node_modules/shipit-cli/bin/shipit production deploy start Running 'deploy:init' task... ...

Validating a model in Mongoose: Best practices for updating data

I am facing an issue with my model. It seems that while creating, incorrect information is prohibited, but when editing, it is allowed. How can I prevent this from happening? var userSchema = new Schema({ cartaoCidadao: { type: String, require ...

Having trouble making Json work with angular.js

I've encountered an issue while trying to retrieve forecast information from an external domain. Despite having both Angular and jQuery loaded, the HTML remains empty with no error messages reported by Chrome. var currentCityread = "Eindhoven ...

Difficulty encountered in resetting progress bar post ajax form submission

Hello, I hope you can assist me with an issue I am facing regarding my progress bar. After submitting the form using AJAX to insert data, my progress bar does not reset. I would like it to reset after clicking the submit button. The progress bar is speci ...

Determine the minimum value in a table row with the help of JavaScript

Currently, I'm using the following code to find certain values in my table. However, I want to eliminate any null fields so that not all blank cells turn red. $('tr').each(function highlight() { var $td = $(this).children('td' ...

Variations in jQuery's append method when dealing with a string, a reference to a jQuery object

Here are multiple ways to add a div element to the body of an HTML document. But what distinctions exist between them and in what scenarios should each be utilized for optimal performance? var newDiv = '<div id="divid"></div>'; $(&ap ...

Convert to TypeScript

I'm currently working on sending WebSocket messages using TypeScript. I have it working in my console with the following code: socket.on('displayHello', function(data) { $.pnotify({ title: "Hello", text: data.from + " t ...

Controlling the visibility of components or elements in Angular through input modifications

Is there a more efficient way to handle button disabling and enabling based on email validation in Angular? I already have form controls set up, but want to make the process cleaner. The goal is to disable the "Get Started" button by default if the email a ...