I'm using API_KEY authentication with AppSync and it works fine for queries and mutations.
Having hard time getting it to work with @aws_subscribe subscriptions. Here is how I try to get the connection:
import { WebSocketLink } from '@apollo/client/link/ws'
import { setContext } from '@apollo/client/link/context'
import {
ApolloClient,
InMemoryCache,
HttpLink,
split,
} from "@apollo/client"
import { getMainDefinition } from '@apollo/client/utilities'
import { API_URI, API_KEY, REALTIME_API_URI } from "@env"
const authLink = setContext((_, { headers }) => {
const token = API_KEY
return {
headers: {
...headers,
'X-Api-Key': API_KEY,
},
}
})
const httpLink = new HttpLink({
uri: API_URI,
})
const wsLink = new WebSocketLink({
uri: REALTIME_API_URI,
options: {
reconnect: true,
lazy: true,
},
})
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query)
return (
kind === 'OperationDefinition'
&& operation === 'subscription'
)
},
authLink.concat(wsLink),
authLink.concat(httpLink),
)
export const gqlClient = new ApolloClient({
link,
cache: new InMemoryCache(),
})
// console.log({ API_URI }, { API_KEY })
As I understand, this questions is asked a lot -- still I'm not able to find satisfactory answer. There is evidence that the latest Apollo client stopped being compatible with AppSync authentication for web sockets, still wondering if there is some kinds of a work around (hack) to pass API_KEY to the appsync subscription so it does not not reject the request and establishes the connection. I really would like to avoid using Amplify, as well as building SNS pub sub myself. Really curious if anyone was able to get this simpler use case to work and can share some sample code.
Here is how I subscribe in the client:
const subscription = CONST.gqlClient
.subscribe({
query: gql`
subscription onSendMessage($chatUuid: String!) {
onSendMessage (chatUuid: $chatUuid) {
chatUuid
createdAt
messageUuid
text
updatedAt
uuid }
}
`,
variables: {
chatUuid,
},
})
.subscribe({
next(data) {
console.log({ data })
},
error({ error }) {
console.log({ error })
},
complete() { console.log("subs. DONE") }, // never printed
})
When I run it, I do see in the log:
Object {
"subscription": Subscription {
"_cleanup": Subscription {
"_cleanup": [Function anonymous],
"_observer": Object {
"complete": [Function complete],
"error": [Function error],
"next": [Function next],
},
"_queue": undefined,
"_state": "ready",
},
"_observer": Object {
"complete": [Function complete],
"error": [Function error],
"next": [Function next],
},
"_queue": undefined,
"_state": "ready",
},
}
But after that nothing ever happens, no error messages, no subscription messages trigger on the mutation invocation. When I subscribe to this subscription in the aws console -- it does trigger just fine. I'm just never able to get it to work in the client app.