apollo-client: WebSocket connection to 'ws://localhost:4000/' failed: Error during WebSocket handshake: Unexpected response code: 400

I can’t figure out what is the problem?

server:

const {ApolloServer, gql, PubSub} = require("apollo-server");
const pubsub = new PubSub();

const typeDefs = gql`
    type Subscription {
        postHello: String!
    }
    
    type Query {
        hello(id: Int!): String!
    }
    
    type Mutation {
        addHello(hello: String!): String!
    }
`;

const POST_ADDED = 'POST_ADDED';

const resolvers = {
    Subscription: {
        postHello: {
            subscribe: () => pubsub.asyncIterator([POST_ADDED])
        }
    },

    Query: {
        hello (obj, args) {
            const arr = ["aaaaaa", "bbbbb", "cccccccc"];
            return arr[args.id]
        }
    },

    Mutation: {
        async addHello (obj, args) {
            await pubsub.publish(POST_ADDED, {postHello: args.hello})

            return args.hello
        }
    }
};

const server = new ApolloServer({typeDefs, resolvers});

server.listen().then(({ url }) => {
    console.log(`🚀  Server ready at ${url}`);
});

client:

import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider, Query } from 'react-apollo';
import gql from 'graphql-tag'
import { ApolloClient } from 'apollo-client';
import { getMainDefinition } from 'apollo-utilities';
import { ApolloLink, split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { InMemoryCache } from 'apollo-cache-inmemory';

import App from './components/App';

const httpLink = new HttpLink({
    uri: 'http://localhost:4000',
});

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

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

const link = ApolloLink.from([terminatingLink]);

const cache = new InMemoryCache();

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

ReactDOM.render(
    <ApolloProvider client={client}>
        <App />
        <Query query={
            gql`
                {
                hello(id: 1)
                }           
`
        }>

            {({ loading, error, data }) => {
                if (loading) return <p>Loading...</p>;
                if (error) return <p>Error :(</p>;

                return <p>{data.hello}</p>
            }}

        </Query>
    </ApolloProvider>,
    document.getElementById('root'),
);

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 3
  • Comments: 18 (1 by maintainers)

Commits related to this issue

Most upvoted comments

try ‘ws://localhost:4000/graphql’

My problem was that I am using an Express server and applying Apollo Server as a middleware. I was not aware that I need to call graphqlServer.installSubscriptionHandlers(expressServer) too, as this was buried deep in the docs. That needs to be called on the HTTP server instance you get returned from expressApp.listen(). Now it is working!

Nevermind, i forgot to add the /graphql at the end of the url just like @vincenterc pointed out.

I had this: ws://localhost:4000

Working: ws://localhost:4000/graphql

Working code just in case anyone else faces this:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";

//Apollo Configurations
import { ApolloClient, InMemoryCache, split, HttpLink } from "@apollo/client";
import { getMainDefinition } from "@apollo/client/utilities";
import { WebSocketLink } from "@apollo/link-ws";

const httpLink = new HttpLink({
  uri: "http://localhost:4000"
});

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

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

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

ReactDOM.render(<App client={client} />, document.getElementById("root"));

you have the single worst documentation on the world , I mean come oooon are u serious with ur docs it’s all disorder

Adding /subscriptions worked for me

Amazing @LuisDev99

Adding the /graphql fixed this issue for me too.

Thank you @danieldunderfelt. You made my year.

Thank you @danieldunderfelt . You saved my day.

This doesn’t sound like an Apollo Client issue, but if anyone thinks it is and can provide a small runnable reproduction using @apollo/client@latest, we’ll take a look. Thanks!

Was a reverseproxy configuration issue for me, not a library issue

Semi-related Apache and NGINX configs, might be good reference to get your own stuff working

I continue to get this issue on my Angular 8 app. I seem to have all the correct code