Search code examples
websocketnuxt.jsapollosubscription

Nuxt Apollo websockets link options?


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.


Solution

  • So after trying a few different ways, this seems like the best way. Simply overwrite the wsClient using a plugin.

    So in nuxt.config.js:

        plugins: [
            { src: "~/plugins/apollo-ws-client.js", mode: "client" }
        ],
        apollo: {
            clientConfigs: {
                default: "~/plugins/apollo-config-default.js"
            }
        },
    
    

    In plugins/apollo-config-default.js:

    export default function() {
        return {
            httpEndpoint: "https://api.8base.com/123456",
            wsEndpoint: "wss://ws.8base.com"
        }
    }
    
    

    Then in plugins/apollo-ws-client.js

    export default ({ app }) => {
        const client = app.apolloProvider.defaultClient
        const token = app.$apolloHelpers.getToken()
    
        if (token) {
            client.wsClient.lazy = true
            client.wsClient.reconnect = true
            client.wsClient.connectionParams = () => {
                return {
                    workspaceId: "123456",
                    token: token
                }
            }
        }
    }
    

    Works great.