I'm trying to configure nginx to work with my socket.io websockets. I have an app with a React frontend and a backend that uses Nestjs and Socket.io. The app runs fine on my local machine but now I'm trying to make it accessible on the internet. I'm using a virtual machine for hosting. The Nestjs back end is running via pm2. I have nginx set up to listen for requests on port 80, and forward them to my frontend build. Nginx serves the frontend build correctly, and it renders in the browser. The frontend code then creates a socket.io connection. When I send messages through the socket, the backend receives them and logs them normally. However, when the backend sends messages back through the socket, the frontend never receives them. I'm thinking there is something wrong with my websocket setup or nginx config, but I'm not seeing any error messages on the server, in the nginx logs, or in the console in the browser. Any help would be appreciated!
This is my Nginx config file located in sites-available
:
server {
listen 80;
server_name www.mydomainname.com; # Replace with your domain
# Frontend
location / {
root /path/to/game-web/build;
try_files $uri $uri =404 /index.html;
}
# Backend API
location /api {
proxy_pass http://localhost:3001; # Adjust port to match your NestJS server
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
# Socket.IO
location /socket.io/ {
proxy_pass http://localhost:3001/socket.io/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
The frontend code that connects to the backend is:
import io from "socket.io-client";
// const socket = io("http://<server-ip-address>:3001");
// const socket = io("http://localhost:3001");
const socket = io("/");
export default socket;
And the main.ts file on the backend is:
import { NestFactory } from "@nestjs/core";
import { GameModule } from "./game/game.module.js";
import { ValidationPipe } from "@nestjs/common";
import mongoose from "mongoose";
async function bootstrap() {
const app = await NestFactory.create(GameModule, {
logger: console,
});
app.useGlobalPipes(new ValidationPipe());
await app.listen(3001);
}
bootstrap();
I would appreciate any thoughts on how I can get the websockets communicating properly, or what I might be missing.