4

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?

aryzing
  • 4,982
  • 7
  • 39
  • 42

1 Answers1

2

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
        ]),
        ...
    }
Branimir
  • 4,327
  • 1
  • 21
  • 33