title: WebSocket error, Unexpected response code: 200 with Nginx and Node.js
body: <p>I'm using a Ubuntu server on DigitalOcean to host an Nginx web server and a Node app that runs a WebSocket server. When attempting to connect to the IP of the server, I get the following message in the console:</p>
  
  <pre><code>WebSocket connection to 'ws://&lt;server's public IP&gt;' failed: Error during WebSocket handshake: Unexpected response code: 200
  </code></pre>
  
  <p>All I did to set up Nginx was to follow <a href="https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04-quickstart" rel="nofollow noreferrer">this guide</a>, which simply tells you to install Nginx and adjust the UFW firewall. I didn't set up server blocks in Step 4, and I haven't touched any other config files.</p>
  
  <p>After that, I put my <code>index.html</code> and <code>client.js</code> files in the <code>/var/www/html</code> directory to be served by Nginx.</p>
  
  <p><code>index.html</code> is a very simple HTML page that runs <code>client.js</code>. That JS file looks like this:</p>
  
  <pre><code>const ws = new WebSocket('ws://&lt;public IP, same as above&gt;:80');
  
  ws.addEventListener('open', () =&gt; {
      const json = { message: 'hello from client!' };
      const jsonString = JSON.stringify(json);
      ws.send(jsonString);
  });
  
  ws.addEventListener('message', event =&gt; {
      const data = JSON.parse(event.data);
      console.log(data);
  });
  </code></pre>
  
  <p>The server side Node app is <code>websocket.js</code>, and it looks like this:</p>
  
  <pre><code>const buffer = require('buffer');
  const http = require('http').createServer();
  const ws = require('ws');
  const wsServer = new ws.Server({ server: http });
  
  wsServer.on('connection', (socket) =&gt; {
      socket.on('message', (msg) =&gt; {
          console.log('received: ' + msg);
          socket.send(Buffer.from('hello from the server!'));
      });
  
      const json = { message: 'hello from server!' };
      const jsonString = JSON.stringify(json);
      socket.send(Buffer.from(jsonString));
  });
  
  http.listen(8080, () =&gt; console.log('listening on 8080'));
  </code></pre>
  
  <p>This file was placed at <code>/root</code> along with <code>node_modules</code>, <code>package.json</code>, and <code>package-lock.json</code>. Serving it alongside the client side code at <code>/var/www/html</code> didn't help. Of course, it was also running thanks to PM2, and I have also tried running without PM2 which made no difference.</p>
  
  <p>Any help is appreciated, please let me know if there's any information I might have missed.</p>