Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 971
Moritz Roessler Avatar asked Dec 05 '25 18:12

Moritz Roessler


1 Answers

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}`
        }
      }
    }
  })
);
like image 153
Anton Avatar answered Dec 08 '25 06:12

Anton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!