r/node • • 6d ago

Why I wanted control over the ws server behind GraphQL subscriptions (and how it works now in NestJS)

If you run GraphQL subscriptions over graphql-ws in NestJS, the ws server used to be created for you, with default options you couldn't touch.

That matters more than it sounds:

  • maxPayload defaults to 100 MiB in ws, so one client can push very large messages at your server.
  • verifyClient lets you reject a connection during the upgrade, before any GraphQL code runs.
  • perMessageDeflate costs CPU and memory per connection, and sometimes you want it off or tuned.

I opened a PR so you can now pass your own WebSocketServer (available in @nestjs/graphql v14.1.0):

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 } },
});

It has to be noServer: true because Nest still owns the HTTP server and hands the upgrade to yours.

Curious what limits others set on websocket servers in production. Do you tune maxPayload or leave the default?

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

9 Upvotes

5 comments sorted by