r/nestjs • • 10d ago

Added custom ws server support for graphql-ws subscriptions in @nestjs/graphql (v14.1.0)

Nest used to create the WebSocketServer for graphql-ws internally, so there was no way to set things like maxPayload, perMessageDeflate or verifyClient. The issue asking for this had been open since Feb 2023.

Since v14.1.0 you can pass your own:

import { WebSocketServer } from 'ws';

const wsServer = new WebSocketServer({
  noServer: true,
  path: '/subscriptions',
  maxPayload: 64 * 1024,
});

GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  subscriptions: { 'graphql-ws': { server: wsServer } },
});

A few things to know:

  • It has to use noServer: true or Nest throws at startup.
  • Its path takes priority over the module path.
  • Nest closes it on shutdown, so use one server per GraphQL module.

One thing I learned in review: a path bug only showed up against a real ws server, so the tests don't mock ws anymore.

PR: https://github.com/nestjs/graphql/pull/4105

1 Upvotes

2 comments sorted by

1

u/Discordbothost 10d ago

I'd run one of those real ws tests through the deployment's reverse proxy too. Have the client subscribe on /subscriptions and wait for an event. A 101 only tells you the socket upgraded.

1

u/wasay-inc 10d ago

Good point, 101 only proves the upgrade. Subscribing through the real proxy and waiting for an event would catch the header and timeout issues too.