title: phoenix.js: WebSocket connection to ws://localhost:4000/socket failed
body: <p>I get this error in the Chrome console on my Phoenix/React app—but, strangely, <strong>not</strong> in incognito mode. Everything is pointed to the same <code>/socket</code> endpoint.</p>
  
  <pre><code>WebSocket connection to 'ws://localhost:4000/socket/websocket?token=blah&amp;vsn=1.0.0' failed: Error during WebSocket handshake: Unexpected response code: 400 
  </code></pre>
  
  <p><a href="https://stackoverflow.com/a/38324142/1342734">Various sources</a> say it's about the transport layer, which makes a bit of sense since this is what's highlighted in the console where the error is:</p>
  
  <pre><code>this.conn = new this.transport(this.endPointURL());
  </code></pre>
  
  <p>The React app finds the endpoint like so:</p>
  
  <pre><code>const API_URL = 'http://localhost:4000/api';
  const WEBSOCKET_URL = API_URL.replace(/(https|http)/, 'ws').replace('/api', '');
  
  function connectToSocket(dispatch) {
    const token = JSON.parse(localStorage.getItem('token'));
    const socket = new Socket(`${WEBSOCKET_URL}/socket`, {
      params: { token },
    });
    socket.connect();
    dispatch({ type: 'SOCKET_CONNECTED', socket });
  }
  </code></pre>
  
  <p><strong>NB:</strong> Amending that line to <code>const socket = new Socket('${WEBSOCKET_URL}/socket/websocket'</code> just makes the error read <code>.../socket/websocket/websocket?...</code>.</p>
  
  <p>The <code>endpoint.ex</code> is pretty standard:</p>
  
  <pre><code>socket "/socket", App.UserSocket
  </code></pre>
  
  <p>None of this points to why the app would work in incognito and load all these errors otherwise, though.</p>