Moritz Roessler
Moritz Roessler

Reputation: 8641

How to pass headers in a GraphQL subscription request?

I am trying to pass custom headers in a GraphQL subscription request, but the headers don't seem to be included in the WebSocket message. I am using the @apollo/client library on the client-side and ApolloServer from 'apollo-server-express' on the server side.

const sub = await client.subscribe({
  query: MY_SUBSCRIPTION,
  variables: {
    // ... subscription variables
  },
  context: {
    headers: {
      'X-Auth-Token': 'my-auth-token',
    },
  },
});

And here's an example of how I'm trying to access the headers on the server-side:

const resolvers = {
  Subscription: {
    mySubscription: {
      subscribe: (_, args, context) => {
        console.log(context.connection.context.headers);
        // ... subscription logic
      },
    },
  },
};

However, the console.log statement in the server-side resolver always prints an empty object, indicating that the headers are not being passed in the WebSocket message.

I've tried researching this issue and have seen some suggestions to use the SubscriptionClient class from the subscriptions-transport-ws library, but I'd prefer to use the WebSocketLink class from @apollo/client if possible.

Any help with passing headers in a GraphQL subscription request using @apollo/client and apollo-server-express would be greatly appreciated. Thank you!

Upvotes: 4

Views: 954

Answers (1)

Anton
Anton

Reputation: 310

WebSockets do not include headers.

To do this, you need to include them manually on the client:

const wsLink = new GraphQLWsLink(
  createClient({
    url: WS_HOST,
    connectionParams: () => {
      const {auth} = store.getState();

      if (!auth.token) return {};

      return {
        // required
        headers: {
          'Authorization': `Bearer ${auth.token}`
        }
      }
    }
  })
);

Upvotes: 0

Related Questions