Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useSubscription not able to create a socket connection #11334

Closed
prabhashms opened this issue Nov 1, 2023 · 6 comments
Closed

useSubscription not able to create a socket connection #11334

prabhashms opened this issue Nov 1, 2023 · 6 comments
Labels
ℹ needs-more-info Needs more information to determine root cause 🛎 subscriptions 🥀 needs-reproduction

Comments

@prabhashms
Copy link

prabhashms commented Nov 1, 2023

Issue Description

This is the client configuration that I'm using.

import { useMemo } from 'react';
import { ApolloClient, InMemoryCache, HttpLink, NormalizedCacheObject, split } from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
import { setContext } from 'apollo-link-context';
import apolloLogger from 'apollo-link-logger';

const CreateApolloClient = (url: string, getAccessToken) => {
  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        authorization: `Bearer ${getAccessToken()}`,
      },
    };
  });

  const httpLink = new HttpLink({ uri: url });
    const wsLink = new GraphQLWsLink(
      createClient({
        url: `ws://localhost:8097/graphql`,
        connectionParams: () => {
          return {
            Authorization: `Bearer ${getAccessToken()}`,
          };
        },
      })
    );

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

  const client: ApolloClient<NormalizedCacheObject> = useMemo(
    () =>
      new ApolloClient({
        link: link,
        cache: new InMemoryCache(),
        credentials: 'include',
      }),
    [authLink]
  );
  return client;
};

export default CreateApolloClient;

When I call useSubscription inside my component, it fails with 'socket closed' error.
It is failing specifically at this line const socket = new WebSocketImpl(typeof url === 'function' ? await url() : url, GRAPHQL_TRANSPORT_WS_PROTOCOL);

Can someone help?

I'm using the following versions:
"react": "18.1.0",
"@apollo/client": "3.7.11",
"graphql": "16.7.1",
"graphql-ws": "5.14.2"

Link to Reproduction

NA

Reproduction Steps

No response

@bignimbus
Copy link
Contributor

Hi @prabhashms 👋🏻 thanks for letting us know about this! Unfortunately it's difficult to know what the issue might be without being able to run the code that you're sharing. I recommend sharing a runnable reproduction so the community and maintainers can help narrow down whether this is an issue with your application code or with Apollo Client. Looking forward to hearing back from you 🙏🏻

@bignimbus bignimbus added 🥀 needs-reproduction 🏓 awaiting-contributor-response requires input from a contributor 🛎 subscriptions ℹ needs-more-info Needs more information to determine root cause labels Nov 2, 2023
@prabhashms
Copy link
Author

Hi @bignimbus,

the only other info I'm able to provide at the moment is that the frontend is running on port 3000 and the backend is running on port 8097. For some reason, the client is making two websocket calls (attached screenshot below). One is to ws://localhost:3000/ws (which succeeds, i guess) and the other is to the wsLink provided in the configuration (which fails).
image

@github-actions github-actions bot removed the 🏓 awaiting-contributor-response requires input from a contributor label Nov 3, 2023
@prabhashms
Copy link
Author

One for piece of information is that I've used create-react-app for building my application. and I'm running my UI behind NGINX reverse proxy.

Following are my nginx configurations:

`
server {

listen 80;

location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;

    # to redirect all the requests to index.html, 
    # useful when you are using react-router

    try_files $uri /index.html; 
}

error_page   500 502 503 504  /50x.html;

location = /50x.html {
    root   /usr/share/nginx/html;
}

}
`

@phryneas
Copy link
Member

phryneas commented Nov 3, 2023

The first one is most likely due to hot module reloading in create-react-app (I assume that is running on port 3000?), so you can safely ignore that.

Generally, the problem at hand looks to be between graphql-ws and your backend - so to remove a lot of unknowns from your setup, you could also try to make a connection between those two points at first - without involving Apollo Client at all.
At this point, I fear we are not the best people to help you here, I'm sorry.

@bignimbus
Copy link
Contributor

I agree with @phryneas - I'm going to close this since it's not actionable for the maintainers but if you need more support please do ask in our Discord or Forum and our community would be happy to give a second set of eyes 👀

@bignimbus bignimbus closed this as not planned Won't fix, can't repro, duplicate, stale Nov 3, 2023
Copy link
Contributor

github-actions bot commented Dec 4, 2023

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
For general questions, we recommend using StackOverflow or our discord server.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Dec 4, 2023
@apollographql apollographql unlocked this conversation Jan 17, 2024
@apollographql apollographql locked and limited conversation to collaborators Jan 17, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
ℹ needs-more-info Needs more information to determine root cause 🛎 subscriptions 🥀 needs-reproduction
Projects
None yet
Development

No branches or pull requests

3 participants