apollographql / apollo-client-nextjs

Apollo Client support for the Next.js App Router
https://www.npmjs.com/package/@apollo/experimental-nextjs-app-support
MIT License
445 stars 34 forks source link

The WS connection failed, I'm not sure where the configuration issue is #338

Open wuzikai18 opened 2 months ago

wuzikai18 commented 2 months ago

image

ApolloWrapper.tsx
"use client"
import { HttpLink, split } from "@apollo/client"
import { GraphQLWsLink } from "@apollo/client/link/subscriptions"
import { getMainDefinition } from "@apollo/client/utilities"
import { ApolloClient, ApolloNextAppProvider, InMemoryCache } from "@apollo/experimental-nextjs-app-support"
import { createClient } from "graphql-ws"

// Helper function to create a client
function makeClient() {
  const httpLink = new HttpLink({
    uri: "https://zion-app.functorz.com/zero/y7xXo5wAY9o/api/graphql-v2",
    fetchOptions: { cache: "no-store" },
    headers: {
      Authorization:
        "xxx",
    },
  })

  const wsClient = createClient({
    url: "wss://zion-app.functorz.com/zero/y7xXo5wAY9o/api/graphql-subscription",
    connectionParams: {
      Authorization:
        "xxx",
    },
    on: {
      connected: () => console.log("WebSocket connected"),
      closed: (event) => console.log("WebSocket closed", event),
      error: (error) => console.log("WebSocket error", error),
    },
  })

  const wsLink = new GraphQLWsLink(wsClient)

  const splitLink = split(
    ({ query }) => {
      const definition = getMainDefinition(query)
      return definition.kind === "OperationDefinition" && definition.operation === "subscription"
    },
    //@ts-ignore
    wsLink,
    httpLink
  )

  return new ApolloClient({
    ssrMode: true,
    cache: new InMemoryCache(),
    link: splitLink,
  })
}

// Component to wrap your app in
export function ApolloWrapper({ children }: React.PropsWithChildren) {
  return <ApolloNextAppProvider makeClient={makeClient}>{children}</ApolloNextAppProvider>
}
'use client';
import { gql, useSubscription } from '@apollo/client';

const MESSAGE_ADDED_SUBSCRIPTION = gql`
  subscription get_messages {
    message {
      id
      created_at
      updated_at
      content
      deleted
    }
  }
`;
const { data, loading, error } = useSubscription(MESSAGE_ADDED_SUBSCRIPTION, {
    skip: typeof window == "undefined",
  });
phryneas commented 2 months ago

You seem to be getting a WebSocket error, but at first look that doesn't seem to be related to Apollo Client. Can you try to remove AC from the picture and report back if it works opening a direct WebSocket connection without Apollo Client?

Sudhanshu8257 commented 2 weeks ago

is there a demo for setting up client with wss connection

the example provided doesn't that muxh unable to setup in my next 14 app

phryneas commented 2 weeks ago

@Sudhanshu8257 There is nothing different compared to Apollo Client outside of Next.js, you should be able to go with the normal examples.