Subscriptions not working in Next JS

Hi, I am using the Apollo client in my Next JS application. I would like to fetch the real time data via subscriptions.

I followed the below documentation as is

and finally getting the below error

this is how my code inside the _app.js file look like. can anyone suggest me why I am getting this error?

import CssBaseline from "@mui/material/CssBaseline";
import { ThemeProvider } from "@mui/material/styles";
import theme from "../src/theme";
import NavBar from "../components/Navbar";
import FooterComponent from "../components/FooterComponent";
import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";
import { split, HttpLink } from "@apollo/client";
import { getMainDefinition } from "@apollo/client/utilities";

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

const wsLink = new GraphQLWsLink(
  createClient({
    url: "http://localhost:4000/graphql",
  })
);

// The split function takes three parameters:
//
// * A function that's called for each operation to execute
// * The Link to use for an operation if the function returns a "truthy" value
// * The Link to use for an operation if the function returns a "falsy" value
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(),
});

function MyApp({ Component, pageProps }) {
  return (
    <>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <NavBar />
        <ApolloProvider client={client}>
          <Component {...pageProps} />
        </ApolloProvider>
        <FooterComponent />
      </ThemeProvider>
    </>
  );
}

export default MyApp;

Thanks
Venk

Solution: Make wsLink a function variable like the code below.

// src/apollo.ts

import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";


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

const wsLink = () => {
  return new GraphQLWsLink(createClient({
    url: 'ws://localhost:3000/graphql'
  }));
}

export const apolloClient = new ApolloClient({
    link: typeof window === 'undefined' ? httpLink : wsLink(),
    cache: new InMemoryCache(),
  });

// pages/_app.tsx

import { ApolloProvider } from "@apollo/client";
import { apolloClient } from "./apollo";

function MyApp({ Component, pageProps }) {
  return (
    <ApolloProvider client={apolloClient}>
      <Component {...pageProps} />
    </ApolloProvider>
  );
}
1 Like