#Websockets not working on live web app

9 messages · Page 1 of 1 (latest)

floral girder
#

Hi, this code is in my nodejs backend (backend.example.com) server.js file:

const WebSocket = require('ws');

const server = new WebSocket.Server({
        port: 7500
    },
    () => {
        console.log('Server started on port 7500');
    }
);

This code is in my nextjs frontend chat (frontend.example.com/chat) page file:

    React.useEffect(() => {

        ws.current = new WebSocket("ws://localhost:7500");

        ws.current.onopen = () => {
            console.log("Connection opened");
            setConnectionOpen(true);
        };

        ws.current.onmessage = (event) => {
            const data = JSON.parse(event.data);
            setMessages((_messages) => [..._messages, data]);
        };

        return () => {
            console.log("Cleaning up...");
            ws.current.close();
        };
    }, []);

it works fine in localhost but on deployed live server, the websocket is not communicating, what is wrong with my code?

timid socket
#

You can't use localhost on prod

#

Use a relative path instead

#

And use the same port as the rest of the api

floral girder
#

@timid socket hi, frontend is on frontend.example.com and backend is backend.example.com, so in my nextjs frontend I use:

    React.useEffect(() => {

        ws.current = new WebSocket("ws://frontend.example.com:7500");

        ......

    }, []);

?

floral girder
#

EDIT: Have updated the useEffect() to:

    React.useEffect(() => {

        ws.current = new WebSocket("wss://backend.example.com:7500");

        ws.current.onopen = () => {
            console.log("Connection opened");
            setConnectionOpen(true);
        };

        ws.current.onmessage = (event) => {
            const data = JSON.parse(event.data);
            setMessages((_messages) => [..._messages, data]);
        };

        return () => {
            console.log("Cleaning up...");
            ws.current.close();
        };
    }, []);

but still it does not work, If I visit the https://backend.example.com I get Upgrade Required

timid socket
#

You need to configure your reverse proxy and again, might I add, use the same port

#

You probably shouldn't even specify a port so it defaults to 443

floral girder
#

hi, I think I am not using a reverse proxy, I am using aapanel and there is no option for that, I just point the https://backend.example.com domain with A record to the hosting IP