I’m trying to set up an Express server with Socket.IO and deploy it on Netlify. My server was working fine on localhost, but I’m having trouble configuring it to work on Netlify. Here’s what I have so far:
Server Code (api.js in functions directory):
const { createServer } = require("http");
const serverless = require("serverless-http");
const { Server } = require("socket.io");
const app = express();
const server = createServer(app);
const io = new Server(server, {
cors: {
origin: "*",
},
});
io.on("connection", (socket) => {
console.log(`Socket connected: ${socket.id}`);
socket.on("realtime-update", () => {
console.log("Invalidating query");
socket.broadcast.emit("realtime-update-client");
});
socket.on("disconnect", () => {
console.log(`Socket disconnected: ${socket.id}`);
});
});
module.exports = app;
module.exports.handler = serverless(app);
package.json:
"name": "freedive-trainer-socket-server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"build": "netlify deploy --prod"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.19.2",
"netlify-cli": "^17.32.0",
"serverless-http": "^3.2.0",
"socket.io": "^4.7.5"
}
}
netlify.toml:
[build]
functions = "./functions"
[[redirects]]
from = "/socket.io/*"
to = "/.netlify/functions/api"
status = 200
force = true
Client Code (Custom React Query Hook):
import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { io } from "socket.io-client";
import { getAllGroupTrainingQueryKey } from "./groupTraining/useGetAllGroupTraining";
const useRealTimeUpdates = () => {
const queryClient = useQueryClient();
const [socket, setSocket] = useState(undefined);
const port ="https://websocket-io-server.netlify.app/netlify/functions/api";
useEffect(() => {
const socket = io(port, {});
const handleRealtimeUpdate = () => {
try {
queryClient.invalidateQueries({
queryKey: getAllGroupTrainingQueryKey(),
});
console.log("Queries invalidated successfully");
} catch (error) {
console.error("Error invalidating queries:", error);
}
};
socket.on("realtime-update-client", handleRealtimeUpdate);
return () => {
console.log("Disconnecting socket and cleaning up");
socket.off("realtime-update-client", handleRealtimeUpdate);
socket.disconnect();
};
}, [queryClient, socket]);
return socket;
};
export default useRealTimeUpdates;
Problem:
When I try to connect my client (which was working on localhost) to the server deployed on Netlify, I encounter issues and cannot establish a connection. The server responds with a 404 Not Found error.
Questions:
How can I properly configure my Express server with Socket.IO to run on Netlify?
Is there a specific way to handle Socket.IO connections when deploying on Netlify?
If Netlify is not suitable for this setup, are there other free hosting services that support Express and Socket.IO that you would recommend?
Any guidance or examples would be greatly appreciated. Thank you!