How to solve Apollo subscriptions "Error during WebSocket handshake: Unexpected response code: 400"

1.5k Views Asked by At

I have a legacy application working with React and subscribing to a GraphQL backend. Today, I upgraded all my packages especially thoses (I suppopse that they are the origin of my problem but I'm not sure):

  • react-apollo from ^2.4.0 to ^3.1.3

  • apollo-link-ws from ^1.0.14 to ^1.0.19

The working code was this:

import {ApolloClient} from 'apollo-client';
import {HttpLink} from 'apollo-link-http';
import {WebSocketLink} from 'apollo-link-ws';
// Other imports....

const wsLink = new WebSocketLink({
  uri: `ws://localhost:3000/graphql`,
  options: {
    reconnect: true,
  },
});

const splittedLink = split(
  ({query}) => {
    const {kind, operation} = getMainDefinition(query);
    return (
      kind === 'OperationDefinition' && operation === 'subscription'
    );
  },
  wsLink,
  httpLink,
);

const link = ApolloLink.from([
  onError(({graphQLErrors, networkError}) => {
    // Handle graphQLErrors and networkError
  }),
  withClientState({
    //...
    cache
  }),
  splittedLink
]);

export default new ApolloClient({
  link,
  cache
});

So it's the basic code as described on Apollo website but after the upgrade I'm getting this error (when looking on my graphQL response in the network):

Error during WebSocket handshake: Unexpected response code: 400

and in my dev terminal, I see an infinite logs saying:

enter image description here

Remark

In my setupProxy.js I have ws set to true:

const proxy = require('http-proxy-middleware');

module.exports = app => {
  app.use(proxy('/graphql', {
    target: 'ws://my-backend-url:my-backend-port',
    changeOrigin: true,
    ws: true,
  }));
};

Any feedback or experience about this?

0

There are 0 best solutions below