Not getting Apollo Client subscription data

I’m trying to get subscription data on NextJS. The server gives the data if you look through the Explorer:

Client:

import {ApolloClient, createHttpLink, InMemoryCache, split} from "@apollo/client";
import {setContext} from "@apollo/client/link/context";
import {TokenFromCookie} from "../../helpers/TokenFromCookie";
import { createClient } from 'graphql-ws';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import {getMainDefinition} from "@apollo/client/utilities";

const {token} = TokenFromCookie();

const httpLink = createHttpLink({
        uri
    });

    const wsLink =
      typeof window !== "undefined"
        ? new GraphQLWsLink(
            createClient({
                url,
                on: {
                    connected: () => console.log("Connected client!"),
                    closed: () => console.log("Closed ws-connection!"),
                },
            })
        )
        : null;

    const splitLink =
      typeof window !== "undefined" && wsLink != null
        ? split(
            ({ query }) => {
                const def = getMainDefinition(query);
                return (
                    def.kind === "OperationDefinition" &&
                    def.operation === "subscription"
                );
            },
            wsLink,
            httpLink
        )
        : httpLink;

    const authLink = setContext((_, { headers }) => {
        const {token} = useTokenFromCookie();
        return {
            headers: {
                ...headers,
                authorization: token ? `Bearer ${token()}` : "",
            }
        }
    });

    const client = new ApolloClient({
        link: authLink.concat(splitLink),
        cache: new InMemoryCache({addTypename: false}),
        defaultOptions: {
            mutate: { errorPolicy: 'all' },
        },
    });

READ_REGISTER_DATA gql:

subscription ReadRegisterData($equipmentId: Int!, $addressRegistry: Int!) {
        readRegisterData(equipment_id: $equipmentId, address_registry: $addressRegistry) {
            equipment_id
            address_registry
            type_of
            data_from_controller
        }
    }

Hook:

const useSubscriptionReadRegisterData = (equipment_ip:number, address_registry: number) => {
    const { data, error, loading} = useSubscription(READ_REGISTER_DATA, {
        variables: {
            equipmentIp: equipment_ip,
            addressRegistry: address_registry
        }
    });

    console.log("data", data)

    const dataRegisterSubscription = (data) ? data.readRegisterData : null;

    return { dataRegisterSubscription, error, loading }
    }

    export default useSubscriptionReadRegisterData;

In the console writes: The connection is established, then immediately the connection is closed WS connection status 101

When you start listening to a subscription through Explorer, on the server, when outputting data to the log, you can see that there is 1 Listener. When you run in the application, it does not show any Listener

Hi @maleevea :wave: thanks for posting! I’m not the most well-versed in Next.js so maybe there’s something that pops out to other community members that I’ve missed. In order to assist further could you send something runnable that demonstrates the issue? Maybe a repository or codesandbox?

Hi, Jeff. which is better? can I give you read access to the repository in github, or make a separate open project with the same settings?

@maleevea I recommend the latter so the community can learn from it - thanks so much!

Hi, Jeff. Made a separate project with the same parameters and everything works. I will investigate further. Thank you for your time

1 Like