Skn0tt / nextjs-nestjs-integration-example

https://nextjs-nestjs-integration-example.now.sh
156 stars 36 forks source link

It doesn't work with GraphQL WebSockets #9

Closed redbaron76 closed 3 years ago

redbaron76 commented 3 years ago

After implementing the Nest.js GraphQL Module, this solution exposes the Http server in order to run the GraphQL Playground (in http://localhost:3000/api/graphql) but the websocket server seems not to be exported and it is not available at the same URI (as it should be). So GraphQL subscriptions don't work.

Any suggestion regarding how to make this work? Thanks

Skn0tt commented 3 years ago

Next.js is not compatible with websockets AFAIK, so I don‘t think that‘ll be possible.

redbaron76 commented 3 years ago

Well, the ws connection should be performed by ApolloClient through its WebSocketLink connector. It shouldn't involve Next.js itself. Here the problem is that ApolloServer websocket instance is not exposed by the http instance of Nest.js, as ApolloServer http is. That's why Playground is accessible through http but not its ws counterpart.

Here you expose the Nest http listener which binds the ApolloServer http listener:

export async function getListener() {
    if (!listener) {
      // connect to TypeORM / Postgres
      const conn = await dbConnection();
      console.log(`Database connected: ${conn.isConnected}`);

      const app = await NestFactory.create(AppModule, { bodyParser: false });

      // Nest.js available under /api in Next.js
      app.setGlobalPrefix("api");

      await app.init();

      const server: http.Server = app.getHttpServer();

      [listener] = server.listeners("request") as NextApiHandler[];
    }

    return listener;
}

Is it possible to get and expose the ApolloServer's websocket as well? I'm not so good in Nest.js to achieve it, yet.

Thanks

Skn0tt commented 3 years ago

In the kind of setup illustrated in this repository, all incoming connections are handled by Next.js and are then passed on to Nest.js "virtually".

That's what happens here: https://github.com/Skn0tt/nextjs-nestjs-integration-example/blob/master/src/pages/api/%5B...catchAll%5D.ts

Thus, networking limitations of Next.js (such as the non-support of websockets) will also limit what can be done when combined with Nest.js in this way.

You could take a look at nest-next though - it integrates the other way around, and I could well imagine it supporting WebSockets.

In some cases, using a third-party provider like Pusher may also allow you to implement WebSockets.