Connect to wss that uses the same port as the rest of backend using nginx

19 views Asked by At

I've got a domain name and certs for my server (which means I can't have any unsecured connections from the client side ). So I'm using the same certs for my backend, and the same port and server for the webSocket server/connection. It seems it cannot have the same server but different port.. And so I cannot figure out how to make it work with nginx....

the client-side code

useEffect(() => {
// here I try to use a different port to separate configs in nginx for nodejs and ws
        const ws = new WebSocket('wss://myip:8001');

        // // Connection opened
        ws.addEventListener('open', () => {
            ws.send('Connection established');
        });

        // Listen for messages
        ws.addEventListener('message', (event) => {
            setInfoMessages((prev) => {
                return prev?.length ? [...prev, event.data] : [event.data];
            });
        });

        return () => {
            if (ws.readyState === 1) {
                ws.close();
            }
        };
    }, []);

the backend-side code

const app = express();
app.options('*', cors());
app.use(cors());
app.use(express.json());

const privateKey = readFileSync('./privkey.pem', 'utf8');
const certificate = readFileSync('./fullchain.pem', 'utf8');

const credentials = { key: privateKey, cert: certificate };

const httpsServer = https.createServer(credentials, app);

const wss = new WebSocketServer({
    server: httpsServer,
});

wss.on('connection', function connection(ws) {
    console.log('WSS is connected\n');

    // ws.on('message', function message(data) {
    //  console.log('received: %s', data);
    // });

    // ws.send('something');
});

httpsServer.listen(8000, () => {
    console.log(`Server is running on port 8000`);
});

the current nginx config

server {
    listen 80;
    server_name mydomain.com;

    # Redirect all HTTP traffic to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name mydomain.com;

    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;

    location / {
        root /root/media-buyer-ui/build;
        index index.html;
    }

    location ~/(auth|getbalance|getprofit|fetchprice) {
        proxy_pass https://myip:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

    }

}
upstream websocket {
   server localhost:8001;
}

How should I configure the nginx for that? Thanks

1

There are 1 answers

0
Eugene1111 On

I think I got it, I just needed to add an endpoint for the websocket like this on the client

useEffect(() => {
        const ws = new WebSocket('wss://mydomain.com/websocket');
...

and like this in the nginx conf

 location ~/(auth|getbalance|getprofit|fetchprice|websocket) { // HERE
        proxy_pass https://myip:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

    }