4
votes

I am using nginx and proxying to my app that uses socket.io on node.js for the websocket connection.

I get the error above when accessing the app through the domain.

I have configured nginx according to https://github.com/socketio/socket.io/issues/1942 to ensure that websockets are properly proxied to the node.js backend.

My nginx configuration is below:

server {
    listen 80;
    server_name domain.com;

    location / {
        proxy_pass http://xxx.xx.xx.xx:8080;
        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;
    }
}

In my react client, I start the websocket connection this way:

import io from 'socket.io-client';

componentWillMount() {
    this.socket = io();
    this.socket.on('data', (data) => {
        this.state.output.push(data);
        this.setState(this.state);
    });
}

Any advice is appreciated!

edit 1:

After more investigation.

My server set up is as follows:

Domain accessible from internet: web-facing.domain.com
Domain accessible from intranet: internal.domain.com

When I access the app from the intranet, it works fine, but get the error when accessing from the internet.

I suspect it's due to the creation of the socket using this.socket = io() which sets up a socket connection with the current domain.

Since the socket in node is listening to ws://internal.domain.com, when connecting via web-facing.domain.com, the wrong socket, ws://web-facing.domain.com, is created.

So now the question is, how can I create a socket to the internal domain when accessing from a different domain?

edit 2:

I have added app.set('trust proxy', true) to configure Express to accept proxy connections, but it still does not work.

1
Are you sure that your Node server is handling the connections properly (and not throwing any errors)? Have you tried to see if it works when you take Nginx out of the equation? - robertklep
@robertklep It works when I tested on localhost with node using one port and the client on another port. - Jiraffe
Did you also try without nginx but using the browser as a client? The nginx config looks okay to me, I'm using something very similar. - robertklep
@robertklep Yes, the test was done without nginx in the picture. - Jiraffe
I have updated my post with more information. - Jiraffe

1 Answers

3
votes

Turns out there was another reverse proxy in front of my server that I had no control of. Changed my server set up to be directly internet facing and it works as expected.