I'm trying to get websocket subscriptions working with Nuxt Apollo. For my server (8base.com) I need to send along a connectionParams
object with the subscription request.
It seems Nuxt Apollo has a httpLinkOptions
but what I really need is a wssLinkOptions
. Anyone know of a way to do this with Nuxt? Ideally I don't have to replace Nuxt Apollo, as I'm using it all throughout the app.
According to the docs, you can setup a subscription as a WebSocketLink.
https://www.npmjs.com/package/@nuxtjs/apollo/v/3.0.4#example-with-subscription-graphcool-as-example
// Set up subscription
const wsLink = new WebSocketLink({
uri: `wss://subscriptions.graph.cool/v1/${process.env.GRAPHQL_ALIAS}`,
options: {
reconnect: true,
connectionParams: () => {
const token = process.server ? ctx.req.session : window.__NUXT__.state.session
return {
Authorization: token ? `Bearer ${token}` : null
}
}
}
})
And here's the full example:
Nuxt Config:
// nuxt.config.js
apollo:{
clientConfigs:{
default: '~/apollo/client-configs/default.js'
}
}
Default Client Config:
// apollo/client-configs/default.js
import { ApolloLink, concat, split } from 'apollo-link'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'
import 'subscriptions-transport-ws' // this is the default of apollo-link-ws
export default (ctx) => {
const httpLink = new HttpLink({uri: 'https://api.graph.cool/simple/v1/' + process.env.GRAPHQL_ALIAS})
const authMiddleware = new ApolloLink((operation, forward) => {
const token = process.server ? ctx.req.session : window.__NUXT__.state.session
operation.setContext({
headers: {
Authorization: token ? `Bearer ${token}` : null
}
})
return forward(operation)
})
// Set up subscription
const wsLink = new WebSocketLink({
uri: `wss://subscriptions.graph.cool/v1/${process.env.GRAPHQL_ALIAS}`,
options: {
reconnect: true,
connectionParams: () => {
const token = process.server ? ctx.req.session : window.__NUXT__.state.session
return {
Authorization: token ? `Bearer ${token}` : null
}
}
}
})
const link = split(
({query}) => {
const {kind, operation} = getMainDefinition(query)
return kind === 'OperationDefinition' && operation === 'subscription'
},
wsLink,
httpLink
)
return {
link: concat(authMiddleware, link),
cache: new InMemoryCache()
}
}
The Client Config subscription should work using the Vue Apollo model: https://apollo.vuejs.org/guide/apollo/subscriptions.html#setup
If you just need the basics, you may also be able to just specify your HTTP and WS endpints:
apollo:{
clientConfigs:{
default:{
httpEndpoint: YOUR_ENDPOINT,
wsEndpoint: YOUR_WS_ENDPOINT
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With