I am trying to implement Subscriptions from Apollo Client in my next.js application. I have used @graphql-codegen/cli to implement queries and mutations, so I just want to use Apollo for Subscriptions.
Here is my code:
import "@/styles/globals.scss";
import type { AppProps } from "next/app";
import { QueryClientProvider, QueryClient } from "@tanstack/react-query";
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
HttpLink,
split,
} from "@apollo/client";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";
import { getMainDefinition } from "@apollo/client/utilities";
const wsLink = new GraphQLWsLink(
createClient({
url: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT as string,
})
);
const httpLink = new HttpLink({
uri: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT as string,
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
httpLink
);
export const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnMount: true,
refetchOnWindowFocus: false,
},
},
});
export default function App({ Component, pageProps }: AppProps) {
return (
<QueryClientProvider client={queryClient}>
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
</QueryClientProvider>
);
}
I am getting this error:
Error: WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`
at createClient (file:///E:/work/Slayr/slayr-web/node_modules/graphql-ws/lib/client.mjs:73:15)
at eval (webpack-internal:///./src/pages/_app.tsx:28:153) {
page: '/'
I tried importing WebSocket from 'ws' and passing it to createClient but then I was getting this error instead
Unhandled Runtime Error
Error: Invalid WebSocket implementation provided