'Web socket problem when adding subscriptions in URQL client
I am using URQL Client with Apollo server, now I am trying to handle subscriptions on URQL client, but I can't seem to make the web socket work. Hope someone can help me thank you. I think there's a problem in client-side, not the communication between server and client yet.
Below is my code that I added in my client:
import { SubscriptionClient } from "subscriptions-transport-ws";
const subscriptionClient = new SubscriptionClient(
"ws://localhost:4000/subscriptions",
{
reconnect: true,
}
);
const CreateUrqlClient = (ssrExchange: any, ctx: any) => {
let cookie = "";
if (isServer()) {
cookie = ctx?.req?.headers.cookie;
}
return {
url: process.env.NEXT_PUBLIC_API_URL,
fetchOptions: {
credentials: "include" as const,
headers: cookie
? {
cookie,
}
: undefined,
},
exchanges: [
dedupExchange,
subscriptionExchange({
forwardSubscription: (operation) =>
subscriptionClient.request(operation),
}),
cacheExchange,
errorExchange,
ssrExchange,
fetchExchange,
],
};
};
export default CreateUrqlClient;
And I encountered the error below (Server Error Error: Unable to find native implementation, or alternative implementation for WebSocket!). Consequently I also tried adding ws (does not work on browser) and WebSocket itself (not sure how to use correctly), but I still can't make it work.
Solution 1:[1]
Try
const subscriptionClient =process.browser ? new SubscriptionClient('ws://localhost:4000/subscriptions', { reconnect: true }) as any : null;
That get it working for me.
Solution 2:[2]
I fixed a similar problem by following this pattern -
import NodeWebSocket from 'ws';
const wsClient = createWSClient({
url: `ws://localhost:8443/graph`,
webSocketImpl: typeof window === 'undefined' ? NodeWebSocket : WebSocket
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | eglease |
Solution 2 | brendangibson |