How to dynamically change Apollo Web Socket Link URI?

2.2k Views Asked by At

Currently I've set up Apollo's web socket link like so:

const wsLink = new WebSocketLink({
  uri: `ws://example.com/graphql?token=${getToken()}`,
  options: {
    reconnect: true,
    connectionParams(): ConnectionParams {
      return {
        authToken: getToken(),
      };
    },
  },
});

This works fine while the connection lasts, but fails when the connection needs to be re-established if the token in the query string has expired.

The way the infra I'm dealing with is set up requires this token to be set as a query param in the URI. How can I dynamically change the URI so that I may provide a new token when the connection needs to be re-established?

1

There are 1 best solutions below

0
On

You can set property wsLink.subscriptionClient.url manually (or create a new subscriptionClient instance?) in function setContext https://www.apollographql.com/docs/link/links/context/.

For example:

import { setContext } from 'apollo-link-context'
...

    const wsLink = your code...     

    const authLink = setContext(() => {
        wsLink.subscriptionClient.url = `ws://example.com/graphql?token=${getToken()}`
    })

    ...

    const config = {
        link: ApolloLink.from([
            authLink,
            wsLink
        ]),
        ...
    }