Search code examples
javascriptreactjswebsocketgraphqlapollo-client

Error: Socket closed with event 1002 in apollo client


im trying to make a subscription from apollo client to the server , In the server i use apollo-server-express.

The subscription works fine in the graphql playground but when I try to connect my client to the server I get this error.

Here is the part of code where i use useSubscription

  1. Messsage.js (client)
const MESSAGE_CREATED_SUBSCRIPTION=gql`
subscription{
  messageCreated{
    content
    from
    to
  }
}
`

const {data:messageData,error:messageError}=useSubscription(MESSAGE_CREATED_SUBSCRIPTION)

useEffect(()=>{
console.log(messageError)
},[messageData,messageError])


2.index.js (client)


const authLink = setContext((req) => {
  let token = localStorage.getItem("token");
  return {
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
    },
  };
});
let httpLink = createHttpLink({
  uri: "http://localhost:4000/graphql",
});

const wsLink = new GraphQLWsLink(
  createClient({
    url: "ws://localhost:4000/graphql",
    reconnect:true,
    connectionParams: {
      authToken: `Bearer ${localStorage.getItem("token")}`,
    },
  })
);
httpLink=authLink.concat(httpLink)
const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === "OperationDefinition" &&
      definition.operation === "subscription"
    );
  },
  wsLink,
  httpLink
);

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

The error message I've been getting

Error: Socket closed with event 1002 
    at Object.error (index.ts:68:1)
    at client.mjs:411:1

3.The network tab enter image description here

enter image description here


Solution

  • I had the same issue when

    • I was tried to use @apollo/client on the client-side.
    • even though subscriptions worked perfectly with the react-apollo package
    • even though subscriptions worked perfectly in the apollo studio

    I was facing this because I used the old subscriptions-transport-ws on my gql server...

    • the thing causing the issue was WebSocketLink setup
    • note how we had to change
      • from new GraphQLWsLink(createClient ...
      • into new GraphQLWsLink(SubscriptionClient...
    • details in apollo documentation for this resolution...

    relevant imports in case of subscriptions-transport-ws on the backend and wanting to use @apollo/client on the front-end:

    import { WebSocketLink } from "@apollo/client/link/ws";
    import { SubscriptionClient } from "subscriptions-transport-ws";
    
    const wsLink = new WebSocketLink(
      new SubscriptionClient("ws://localhost:4000/subscriptions", {
        connectionParams: {
          authToken: user.authToken
        }
      })
    );