Using an asynchronous function as a handler for a socketio listener

Trying to integrate authentication into socketio websockets has presented a challenge involving the management of auth tokens. The issue revolves around the fact that the function used to retrieve an updated auth token is asynchronous. It appears that providing an async function to the socketio listener for the "reconnect_attempt" event does not wait for the function to complete before initiating the reconnect process.

Essentially, this piece of code:

socket.on("reconnect_attempt", async () => {
    const token = await getIdToken();
    socket.io.opts.query = { token };
});

fails to set the socket's query.token prior to sending the reconnect request to the server. Consequently, when a reconnection is attempted after a token expiration, the expired token gets sent while the new one is still being fetched.

Is there a way to configure socketio to ensure that it waits for the completion of the listener's handler function before triggering the reconnect request? If not, I might need to take a proactive approach by refreshing the token beforehand and storing it within the app. However, I'm curious if there is another workaround for this scenario.

Answer №1

One interesting thing to note is that the "reconnect_attempt" callback does not actually interrupt the request being made; rather, it allows you to listen when a reconnection attempt is being made. A better approach might be to configure your socketio connection to not automatically reconnect and instead subscribe to the disconnect event. This way, you can properly handle token generation and initiate a new request accordingly.

const socket = io({
  autoConnect: false
});

// The 'socket.disconnected' property indicates whether the connection is up or down
socket.on('connect', () => {
  console.log(socket.disconnected); // false
});

Learn more about the 'reconnect_attempt' event here

Answer №2

I can share two different approaches to accomplish the task at hand. Firstly, you can convert your asynchronous function into a synchronous one.

function waitFor(promise) {
  let returnValue, isDone;
  promise.then(result => {returnValue = result, isDone = true});
  while (!isDone) {}
  return returnValue
}

socket.on("reconnect_attempt", waitFor(
    (async () => {
      const token = await getIdToken();
      socket.io.opts.query = { token };
    })()
  )
);

Alternatively, you can opt to turn off reconnection and handle the reconnection process manually.

socket.reconnection(false);
socket.on("disconnect", async () => {
    const token = await getIdToken();
    socket.io.opts.query = { token };
    socket.open()
    // Add logic for reconnect attempt limit, delay, etc.
});

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 change the text color of a table when hovering over an image using Javascript?

UPDATE: I believe I have solved the issue! However, if anyone has suggestions on a better way to achieve this, I am open to learning. I'm still fairly new to Javascript! I have an image and a table containing text. My goal is to change the color of S ...

combining elements in JavaScript

I have two object arrays that look like this: arr1 = [ { 'v1': 'abcde', 'pv_45': 13018, 'geolocation': '17.340291,76.842807' }] arr2 =[{ 'v1':'abcde', 'pv_50&apos ...

Generating small image previews in JavaScript without distorting proportions

I am currently working on a client-side Drag and Drop file upload script as a bookmarklet. To prepare for the upload process, I am utilizing the File API to convert the images into base64 format and showcase them as thumbnails. These are examples of how m ...

Issue with response.split(",")[0] in Internet Explorer

Here is the code snippet I am struggling with: <script> $('#blah').on('click', function(){ $.ajax({ type: 'POST', url: 'ajax.php', data: {"xxx":"yyy", "zzz":"nnn ...

PHP retrieve rows with matching first words - must be exact matches

$companies = array( array('id' => '1','name' => 'Fifo Limited'), array('id' => '2','name' => 'FIFO Ltd'), array('id' => '3','name& ...

Unable to assign an IP address to an Express JS application

Struggling to test a specific endpoint in Express, but consistently encountering a 404 error. var express = require("express") var app = express() //var http = require('http').Server(app) app.get('/', function(req,res){ res. ...

Using PHP to calculate the total number of records within an HTML document

I am currently working on a PHP script to establish a connection with my MySQL database in order to retrieve the total number of users registered on my forum by counting the records in the table. https://i.sstatic.net/ZR0IY.png The PHP script should disp ...

Issue with Electron dialog.showOpenDialog() Filters malfunctioning

Recently, I've been working on a modified version of an IDE on GitHub and encountered a major issue where the files were being saved to cookies instead of the computer. This prompted me to find a way to save and open files efficiently. While I managed ...

React import syntax using dot notation

I've noticed a trend in many react frameworks recommending dot notation for imports. For example, instead of: import Y from 'X/Y'; <Y /> they suggest using: import X from 'X'; <X.Y /> Both methods seem to work ...

The React Bootstrap modal fails to display the value of an argument passed through a parameter

I am currently working on a project that utilizes React for its front end development. Below is the code snippet: import React, {useState} from 'react'; import Tree from 'react-d3-tree'; import { useCenteredTree } from "./helpers&q ...

A small computation

How can I modify this code to calculate the total price #ttc by multiplying #totalcout with #marge Currently, I am able to add amounts when checkboxes are clicked, but I am struggling with integrating the multiplication for calculating the Total Price (TT ...

Continuously transmitting PNG files to a server. I intend to instruct the receiving browser to automatically refresh at set intervals

I have a continuous task where my code is uploading a png to an http server every few seconds. I am looking for a way to implement some kind of marker that will trigger the browser to automatically refresh every 500ms, either through browser-side javascrip ...

Creating an outlined effect on a transparent image in a canvas: step-by-step guide

Currently, I am working on creating transparent images using canvas in HTML5 and I would like to incorporate borders into them. The issue I'm facing is that the "Stroke" property does not consider the transparency of the image and applies it as if it ...

Retrieving data from a nested object with varying key names through ng-repeat

My JSON object contains various properties with unique names: var definitions = { foo: { bar: {abc: '123'}, baz: 'def' }, qux: { broom: 'mop', earth: { tree: 'leaf', water: 'fi ...

The patch method is failing to upload using axios

In my project using Laravel 5.8 and Vue.js 2, I have encountered a problem with the .vue file: let formData = new FormData(); formData.append('name', this.name); formData.append('image',this.image) formData.a ...

obtain the text content from HTML response in Node.js

In my current situation, I am facing a challenge in extracting the values from the given HTML text and storing them in separate variables. I have experimented with Cheerio library, but unfortunately, it did not yield the desired results. The provided HTML ...

Encountering mixed content error on webpack development server

My React based website is currently running on Cloud9 using webpack-dev-server, which serves content over https. However, I have encountered an issue when attempting to make ajax (network) requests to external http links. The error message I receive is: ...

Issue with mobx @inject not generating distinct (enhanced) component

Trying to get a React application up and running with mobx for state management has been quite the challenge. The store is set up like this: ApplicationStore.js import { observable, action, reaction } from 'mobx'; class ApplicationStore { ...

Appending the desired URL to the existing URL using an Ajax callback

Ever since I started working on a Drupal 7 project, I have been facing an issue with making an ajax call back. The problem arises when the URL I intend to use for the callback gets appended to the current page the user is viewing. It's quite puzzling ...

The operating system MacOS requests permission from the parent Node process rather than the child process

When using the child_process module, I encountered a situation where MacOS prompts for permissions for the parent process instead of the spawned child. For instance, running the code below in the terminal results in MacOS asking for permission for "Termina ...