Search code examples
reactjsgraphqlnestjssubscriptionapollo-client

Apollo-Client with subscriptions: failed: Error during WebSocket handshake: Unexpected response code: 400


I have a reactjs application with nestjs + graphql + subscription server.

I have successfully setup graphql+subscriptions on the server. I can test it through the interactive playground interface. Everything works fine on server side.

Now I have been trying to setup graphql subscription on the client with no success. I have looked at countless tutorials and similar (or even same) github issues. Here is my client setup.

I don't know what I am doing wrong:

import React from 'react';
import { ApolloProvider } from '@apollo/react-hooks';
import { ApolloClient } from 'apollo-client';
import { getMainDefinition } from 'apollo-utilities';
import { split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { IntrospectionFragmentMatcher, InMemoryCache } from 'apollo-cache-inmemory';


// this is a factory function I'm using to create a wrapper for the whole application

const ApolloProviderFactory = (props) => {

  const { graphQlUrl, introspectData } = props;

  const httpLink = new HttpLink({
    uri:`http://${graphQlUrl}`,
  });

  const wsLink = new WebSocketLink({
    uri: `ws://${graphQlUrl}`,
    options: {
      reconnect: true,
    },
  });

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

  const fragmentMatcher = new IntrospectionFragmentMatcher({
    introspectionQueryResultData: introspectData,
  });
  const cache = new InMemoryCache({ fragmentMatcher });

  const client = new ApolloClient({
    link,
    cache,
  });

  // this component will wrap the whole application
  const ApolloWrapper = ({ children }: ApolloWrapperProps) => (
    <ApolloProvider client={client}>{children}</ApolloProvider>
  );
  return ApolloWrapper;
}

Here is the error I'm getting when I run the app:

enter image description here

Any help would be greatly appreciated.


Solution

  • I had the pace.js library which was somehow interfering with the whole socket thing. After I disabled it, every thing works as expected.