11

I'm trying to upgrade our NestJS GraphQL subscriptions server to utilize graphql-ws rather than the current subscriptions-transport-ws (as suggested by the NestJS documentation). I upgraded the NestJS version to

    "@nestjs/core": "^8.0.6",
    "@nestjs/graphql": "^9.0.4",
    "@nestjs/platform-express": "^8.0.6",
    "graphql": "^15.5.3",
    "graphql-tools": "^8.2.0",
    "apollo-server-express": "^3.3.0",

And after, I added the subscriptions option to the App.Module:

    GraphQLModule.forRoot({
      autoSchemaFile: true,
      sortSchema: true,
      playground: true,
      installSubscriptionHandlers: true,
      subscriptions: {
        'graphql-ws': true
      },
    }),

However when I subscribe (in playground) to a previously working subscription, I get:

{
  "error": "Could not connect to websocket endpoint ws://localhost:8880/graphql. Please check if the endpoint url is correct."
}

And in the console I get:

WebSocket protocol error occured. It was most likely caused due to an unsupported subprotocol "graphql-ws" requested by the client. graphql-ws implements exclusively the "graphql-transport-ws" subprotocol, please make sure that the client implements it too.

Things I have tried:

  • Adding the graphql-ws package
  • Upgrading the NestJS version again
  • Removing the installSubscriptionHandlers option from config
  • Setting graphql-ws configs instead of passing true
  • Using the WebSocket Test Client Google Chrome extension instead of Playground

But none have worked. Sorry for the long post. How can I fix this?

BehzadV
  • 167
  • 3
  • 10

2 Answers2

13

At the time of release of Apollo Server 3, the protocol used in the graphql-ws library is not yet supported by GraphQL Playground or Apollo Explorer.

see here

It's only advisable to use graphql-ws if interacting with subscriptions via playground is not of much use to you and you're okay interacting with subscriptions solely from your own client that has been setup to use graphql-ws.

To setup your client to use graphql-ws with Apollo. see here.

Efosa
  • 146
  • 1
  • 2
  • Oh well, that's disappointing. So the Google Chrome extension failed for the same reason as well? – BehzadV Sep 25 '21 at 08:27
12

This will do the job:

subscriptions: {
    'graphql-ws': true,
    'subscriptions-transport-ws': true,
  },

As mentionned in the doc:

HINT

You can also use both packages (subscriptions-transport-ws and graphql-ws) at > the same time, for example, for backward compatibility.

Julien L
  • 121
  • 1
  • 3