Issue with AWS API Gateway and Restful API: socket.io encounters an error stating that the route '/socket.io?EIO=4&t=xxx&transport=polling' does not exist

My backend API services are hosted on AWS using API Gateway and EC2 instance. The backend is built with Node.js/Express JS, and socket.io is used for real-time messaging.


const initializeExpress = (): void => {
  const app = express();
  let http = require("http").createServer(app);
  let io = require("socket.io")(http, {
    cors: {}
  });

  io.on("connection", function(socket: any) {
    socket.on("hello", (res) => {
      console.log('on hello: ', res); 
    });
  });

  const server = http.listen(parseInt(process.env.PORT) || 3001, function() {
    console.log("listening on *:3001");
  });

  // register some middlewares for web socket
  ...
};

The WebSocket connection works fine in the local environment at 127.0.0.1:3001. However, when moving to the AWS API Gateway configuration, all other API endpoints work except the WebSocket request which returns a 404 error.


error: User undefined got Error on NLB-myapp-internal-1234123.elb.ap-northeast-1.amazonaws.com/socket.io?EIO=4&t=Nv2sCMO&transport=polling: Error: Route '/socket.io?EIO=4&t=Nv2sCMO&transport=polling' does not exist.

Even though the restful API created in AWS API Gateway is configured correctly with proxy integration, the route /socket.io seems to be missing.

I have followed suggestions from related answers but still face the issue. The setup in Express for socket.io is as follows:


  const app = express();
  let http = require("http").createServer(app);
  let io = require("socket.io")(http, {
    cors: {}
  });
  const server = http.listen(parseInt(process.env.PORT) || 3001, function() {
    console.log("listening on *:3001");
  });

In the local dev environment without API Gateway, everything works smoothly once the request reaches the target port. Why, in the AWS API Gateway setup, does it complain about the non-existent /socket.io route even after successfully delivering the request to the target port?

What am I missing here?

Answer №1

When attempting to connect to the backend using socket io, it uses the endpoint socket.io as you have discovered. However, AWS Socket Gateway simplifies this process by transforming sockets into REST, following this path: Sockets -> GW -> REST. Your current approach involves: Sockets -> GW -> socket.io

Unfortunately, this method will not work for two main reasons:

  1. AWS GW does not support sockets on the backend.
  2. Socket IO does not adhere to the standard web socket protocol, making it incompatible with AWS.

Another important point to consider is that if custom domains are utilized for your gateway, defining socket.io in the path may allow for the handshake to occur initially. However, due to the issues mentioned above, the connection will be dropped and re-established.

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 I leverage Cygwin in the Windows environment to create Node.js applications using Yarn?

Starting to work with yarn is my goal. Currently, I am using cygwin on a Windows system. When I launch and type: $yarn init I encounter the following error: $ yarn init yarn init v1.12.3 error An unexpected error occurred: "Can't answer a question ...

Generate a set of random filtered results using mongoose in a Node.js environment

In my attempt to create a simple app for generating random exams, I have defined the following schemas: Question schema: var questionSchema = mongoose.Schema({ text: String, type: { type: String, enum: ['multichoice', 'numerica ...

Using Sequelize to send data from the client-side to the server-side

I am currently developing a project for a fictional library database and website interface. I am facing an issue where only 2 out of the 4 new loan form inputs are being passed to the req.body. Even though all items have a name attribute, it seems like onl ...

What is the mechanism by which a callback function operates in conjunction with Azure Blob's createReadStream method for streaming

I have a function that successfully retrieves a stream object containing a blob from Azure Storage: module.exports.readFileToStream = function(fileSpec, callback){ return blobService.createReadStream(fileSpec.container, fileSpec.file, function(err, res ...

Difficulty encountered while executing Protractor tests with Selenium Server

Attempting to Execute Protractor/Jasmine/Selenium End-to-End Tests Currently in the process of running end-to-end tests using Protractor with the standalone Selenium server and the chrome driver. Encountering a Selenium server error when attempting to ru ...

Error during live-server npm installation: symlink issue persists even with root/admin privileges

In my current project, I am following a tutorial on AngularJS from the book titled "Unraveling AngularJS 1.5 (With Over 130 Complete Samples" by István Novák, which stipulates the need for installation of Node.js. The appendix of this book provides comma ...

Having trouble running Npm in PowerShell after installing NodeJs?

Upon completing the installation of NodeJs on Windows 11, I encountered an issue. When I run "node -v" in CMD and PowerShell, it displays the node version correctly. However, when I try running "npm -v", it creates a problem. For NPM, running "npm -v" in ...

Redis data retrieval is successful on the second attempt

I am utilizing a Redis database along with express routing to create an API. My stack includes node.js and ioredis as well. The process involves connecting to Redis, fetching keys related to a specific date, and then retrieving the data associated with th ...

Setting up a personalized JSPM registry configuration

I have chosen to use Verdaccio as the platform for hosting a private package. In my current project, I am looking to incorporate this package locally. The package has been successfully published and is now hosted on Verdaccio running on localhost (http://l ...

Access-Control-Allow-Methods is not permitting the use of the DELETE method in the preflight response for Angular 2

I am having trouble deleting a record in mongodb using mongoose. Here is the code snippet from my component: deleteProduct(product){ this._confirmationService.confirm({ message: 'Are you sure you want to delete the item?', ...

Having difficulty integrating requireJS and Node's Require in a single TypeScript project

I currently have a TypeScript project that is intended to work with both Node and the browser. In some scripts, I'm utilizing Node's require(), while in others requireJS's require(). The structure of my project directory is as follows: myPr ...

An error occurred while checking the Node.js npm version in internal/modules/cjs/loader.js at line 892

In Node.js, I am encountering an error while checking the npm version. The error message is as follows: internal/modules/cjs/loader.js:892 throw err # below error occurs npm -v https://i.stack.imgur.com/UouXf.jpg # below error occurs npm -v readline-sy ...

Is it safe to make changes to the socket.rooms set in Socket.io?

My intention with Socket.io is to monitor the specific pages that users are visiting, as well as the elements they interact with on those pages. To achieve this, I need a structured hierarchy within the rooms. Merely appending the room to the previous one ...

Utilize Express and Passport to enable simultaneous login for various 'local' accounts

Apologies in advance for any language or technical errors, as English and Node are not my strong suits. I have resorted to using Google Translation for assistance since solutions within my local sphere are unavailable. EQUIPMENT USED Ubuntu 16.04 locally ...

Enhancing NextJS/playwrights with the latest nodejs upgrade?

I am facing issues with my Vercel build due to Playwright's outdated Node.js version: Error: Node.js version 12.x is deprecated. Starting from 2022-08-09, builds will fail unless the Node.js Version is set to 16.x in Project Settings. This change wa ...

Nodemon causing server to fail to start or connect

I recently set up a new project using Express, Node, and Nodemon. I configured the basic files to ensure it starts properly, but when I run npm start in the terminal, it seems to initiate without any errors being displayed regarding the server's locat ...

Navigating to a different intent within the DialogFlow Messenger fulfillment can be done by utilizing the 'agent.setFollowupEvent(targetIntentEventName)' method

I am currently exploring ways to initiate another DialogFlow Intent (using its event) from a webhook server built with node.js. This will occur after gathering the user's email address, verifying their registration status by sending a POST API request ...

The dependency that was installed in the node_modules directory is now showing as missing the

I have encountered an issue with 2 TS packages. The first package, project-1, is installed as a dependency in the second package, project-2. While I am able to import and access all type definitions of project-1 in project-2, the dependencies (node_modules ...

Customized properties on the file object

I am looking for a way to store files on a server with custom File properties. I have added some properties on the client side like so: let file = new File([blob], 'flower.jpg') file.custom = "another properties" This outputs the following: c ...

An error keeps popping up in the console saying "Module not found"

import React from 'react' import './sidebar.css' import logo from './images/' const sidebar = () => { return ( <div className='sideBar grid'> <div className='logoDiv flex&apo ...