apollographql / subscriptions-transport-ws

:arrows_clockwise: A WebSocket client + server for GraphQL subscriptions
https://www.npmjs.com/package/subscriptions-transport-ws
MIT License
1.52k stars 342 forks source link

Unhandled GraphQL subscription error Error: Cannot read property 'load' of undefined #853

Closed elisalimli closed 2 years ago

elisalimli commented 3 years ago

My packages:

  "dependencies": {
    "@apollo/client": "^3.3.11",
    "@chakra-ui/react": "^1.3.3",
    "@emotion/react": "^11.1.5",
    "@emotion/styled": "^11.1.5",
    "apollo-link-context": "^1.0.20",
    "autoprefixer": "^10.0.4",
    "formik": "^2.2.6",
    "framer-motion": "^3.3.0",
    "graphql": "^15.5.0",
    "graphql-tag": "^2.11.0",
    "next": "latest",
    "next-apollo": "^5.0.4",
    "next-themes": "^0.0.10",
    "postcss": "^8.1.10",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scroll-to-bottom": "^4.1.0",
    "subscriptions-transport-ws": "0.9.15",
    "tailwindcss": "^2.0.2"
  },

I got error like this : Unhandled GraphQL subscription error Error: Cannot read property 'load' of undefined

import {
  ApolloClient,
  ApolloLink,
  createHttpLink,
  InMemoryCache,
  split,
} from "@apollo/client";
import { WebSocketLink } from "@apollo/client/link/ws";
import { getMainDefinition } from "@apollo/client/utilities";
import { setContext } from "apollo-link-context";
// import { PaginatedPosts, Subscription } from '../generated/graphql';
import { NextPageContext } from "next";
import createWithApollo from "./createWithApollo";

const createClient = (ctx: NextPageContext) => {
  // const httpLink = createHttpLink({
  //   uri: "http://localhost:4000/graphql",
  //   credentials: "include",

  //   headers: {
  //     cookie:
  //       typeof window === "undefined" ? ctx?.req?.headers.cookie : undefined,
  //   },
  // });

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

  const middlewareLink = setContext(() => ({
    credentials: "include",
    headers: {
      cookie:
        typeof window === "undefined" ? ctx?.req?.headers.cookie : undefined,
    },
  }));

  const httpLinkWithMiddleware = middlewareLink.concat(httpLink);

  const wsLink =
    typeof window === "undefined"
      ? httpLink
      : new WebSocketLink({
          uri: "ws://localhost:4000/graphql",
          options: {
            reconnect: true,
          },
        });

  const link = split(
    ({ query }) => {
      const { kind, operation } = getMainDefinition(query);
      return kind === "OperationDefinition" && operation === "subscription";
    },
    wsLink,
    httpLinkWithMiddleware
  );

  // export default new ApolloClient({
  //   link,
  //   cache: new InMemoryCache(),
  // });

  return new ApolloClient({
    uri: "http://localhost:4000/graphql",
    link,
    cache: new InMemoryCache(),
  });
};

export const withApollo = createWithApollo(createClient);