#GraphQL Subscriptions Not Working with Custom WebSocket Gateway in NestJS

1 messages · Page 1 of 1 (latest)

rich void
#

GraphQL Subscriptions Not Working with Custom WebSocket Gateway in NestJS

#

I'm encountering an issue where GraphQL subscriptions fail when used alongside a custom WebSocket gateway in my NestJS app. Subscriptions throw the following error:

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

Setup Overview

  • GraphQL: Configured with graphql-ws for real-time subscriptions.
  • Custom WebSocket Gateway: Used for IoT devices, with a verifyClient method that authenticates connections using query parameters.

Custom Gateway Example

@WebSocketGateway({
  path: '/devices',
  verifyClient: async (info, cb) => {
    const uid = new URL(info.req.url, 'http://localhost:3000').searchParams.get('uid');
    const deviceExists = await prisma.productionDevice.findUnique({ where: { chipId: uid } });
    cb(!!deviceExists, 200, 'Verified');
  },
})
export class DevicesWsGateway {
  handleConnection(client: any): void {
    // Add client logic
  }
  handleDisconnect(client: any): void {
    // Remove client logic
  }
}

GraphQL Config:

GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
  subscriptions: { 'graphql-ws': true },
});

Environment:

  • NestJS: ^10.4.15
  • GraphQL: ^16.10.0
  • GraphQL-WS: ^5.16.2

Main File:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.useWebSocketAdapter(new WsAdapter(app));
  await app.listen(3000);
}
bootstrap();
#

Questions:

  1. How can I use GraphQL subscriptions (/graphql) and a custom WebSocket gateway (/devices) without conflicts?
  2. Is the WsAdapter causing a conflict with graphql-ws?
  3. What changes are needed to make both features work seamlessly?

Relevant Dependencies:

{
  "@nestjs/apollo": "^12.2.2",
  "@nestjs/graphql": "^12.2.2",
  "@nestjs/platform-ws": "^10.4.15",
  "graphql": "^16.10.0",
  "graphql-ws": "^5.16.2"
}

Looking forward to your suggestions. Thank you!