im trying to make a subscription from apollo client to the server , In the server i use apollo-server-express.
The subscription works fine in the graphql playground but when I try to connect my client to the server I get this error.
Here is the part of code where i use useSubscription
const MESSAGE_CREATED_SUBSCRIPTION=gql`
subscription{
messageCreated{
content
from
to
}
}
`
const {data:messageData,error:messageError}=useSubscription(MESSAGE_CREATED_SUBSCRIPTION)
useEffect(()=>{
console.log(messageError)
},[messageData,messageError])
2.index.js (client)
const authLink = setContext((req) => {
let token = localStorage.getItem("token");
return {
headers: {
Authorization: token ? `Bearer ${token}` : "",
},
};
});
let httpLink = createHttpLink({
uri: "http://localhost:4000/graphql",
});
const wsLink = new GraphQLWsLink(
createClient({
url: "ws://localhost:4000/graphql",
reconnect:true,
connectionParams: {
authToken: `Bearer ${localStorage.getItem("token")}`,
},
})
);
httpLink=authLink.concat(httpLink)
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(),
});
The error message I've been getting
Error: Socket closed with event 1002
at Object.error (index.ts:68:1)
at client.mjs:411:1
3.The network tab
I had the same issue when
@apollo/client
on the client-side.react-apollo
packageI was facing this because I used the old subscriptions-transport-ws
on my gql server...
WebSocketLink
setupnew GraphQLWsLink(createClient ...
new GraphQLWsLink(SubscriptionClient...
relevant imports in case of subscriptions-transport-ws
on the backend and wanting to use @apollo/client
on the front-end:
import { WebSocketLink } from "@apollo/client/link/ws";
import { SubscriptionClient } from "subscriptions-transport-ws";
const wsLink = new WebSocketLink(
new SubscriptionClient("ws://localhost:4000/subscriptions", {
connectionParams: {
authToken: user.authToken
}
})
);