Netlify refusing connection of Socket - Socket IO - Express Server on Netlify

I have a Netlify App running on my Github Repository. When I first set the Netifly Account up the site deployed and Socket Connected.

If I try to deploy the build again, I am receiving the error:

GET http://localhost:8080/socket.io/?EIO=3&transport=polling&t=MkFZwZJ net::ERR_CONNECTION_REFUSED

I have read many SO answers and tried different steps:

  • Setting Port to 8080
  • Adding { transports: ["websocket"], upgrade: false } to my client connection
  • Changing the Client connection from io("http://localhost:8080"); to io() and io("/")
  • Adding the IP addr to my server.listen Call : server.listen(port, "127.0.0.1", () => {...}
  • Tried different Ports [3000, 3001, 3002, 8080, 8081]

I am really confused on why I could get it to work the first time but never again after that. I thought it could be that the port once used closes and you aren’t able to use the same Port again but different ports failed…

Any advice would be great

Server.ts

import bodyParser from "body-parser";
import express from "express";
import { createServer } from "http";
import { createSocket } from "./socket";

const app: express.Application = express();
const port: number = ((process.env.PORT as any) as number) || 8080;

const server = createServer(app);
createSocket(server);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static("./build"));
app.use(express.static(__dirname, { extensions: ["html"] }));

server.listen(port, "127.0.0.1", () => {
  // tslint:disable-next-line:no-console
  console.log(`Listening at http://localhost:${port}/`);
});

socket function

import { listen } from "socket.io";
export function createSocket(server: Server) {
  const io = listen(server);
  io.on("connection", (socket) => {
    console.log("Client connected...");
  });
}

client connection

import io from "socket.io-client";
const socket = io("http://localhost:8080");

Please provide a link to your live site hosted on Netlify
https://sad-gates-ad2a7f.netlify.com/

Hi Zack, welcome to the Netlify Community.

Are you trying this local, or are you expecting this to work on a Netlify deploy?

Trying to run an express server on Netlify is not possible because your deploy directory is pushed out to the CDN edges and only takes static pages and assets. The deploy is not a node container where you have a running instance of node. Node will only exist at the time of your build in the workflow.

If you need a service to serve up an endpoint, Netlify offers functions for your site.

1 Like