timhall / svelte-apollo

Svelte integration for Apollo GraphQL
MIT License
947 stars 68 forks source link

How to add wsLink with headers (auth:token) into the client? #79

Open beebase opened 3 years ago

beebase commented 3 years ago

In this link I've read how to set up httpLink with headers: {authorization: Bearer "+ getToken() } https://github.com/timhall/svelte-apollo/issues/30

I would also like to add a wsLink with: connectionParams: {headers: {authorisation: Bearer + getToken() } but I can't find any example on the internet

chbert commented 3 years ago

@beebase That's how I implemented (not sure if this is the best approach, though):

const wsLink = new WebSocketLink({
  uri: WS_GRAPHQL_ENDPOINT,
  options: {
    lazy: true,
    reconnect: true,
    connectionParams: async () => {
      const token = await getToken();

      return {
        headers: {
          authorization: token ? `Bearer ${token}` : '',
        },
      };
    },
  },
});