Using Secure Websocket on 3 different ports in Nest.js

Viewed 369

I have a Nest-Service with the following main.ts:

async function bootstrap() {
  if (!!environment.production) {
    const app = await NestFactory.create(AppModule, {
      httpsOptions: {
        key: fs.readFileSync(environment.ssl.SSL_KEY_PATH),
        cert: fs.readFileSync(environment.ssl.SSL_CERT_PATH)
      },
    });
    app.useWebSocketAdapter(new WsAdapter(app));
    app.enableCors();
    await app.listen(3077);
  } else {
    const app = await NestFactory.create(AppModule);
    app.useWebSocketAdapter(new WsAdapter(app));
    app.enableCors();
    await app.listen(3077);
  }
}
bootstrap();

And two Gateways within the Service:

@WebSocketGateway(3078)
export class ItemsGateway implements OnGatewayConnection, OnGatewayDisconnect { ... }
@WebSocketGateway(3079)
export class UnitsGateway implements OnGatewayConnection, OnGatewayDisconnect { ... }

Without SSL this is working, but when I use the prod mode I can´t establish a secure connection to domain.tld:3078 and :3079. How can I get the service to listen on all 3 Ports? I think there is the problem, because certs are only attached to the Server listening on Port: 3077, where all my REST-API stuff goes.

Thx, Dom

Edit: This also worked as there was just on WebsocketServer on the same port as the API -> 3077.

Edit 2: I also tried this, but then comes the error that address is in use on the second attempt to create() a server:

async function bootstrap() {
  if (!!environment.production) {
    const httpsOptions = {
      key: fs.readFileSync(environment.ssl.SSL_KEY_PATH),
      cert: fs.readFileSync(environment.ssl.SSL_CERT_PATH)
    };

    const server = express();
    const app = await NestFactory.create(
      AppModule,
      new ExpressAdapter(server)
    );

    app.useWebSocketAdapter(new WsAdapter(app));
    app.enableCors();

    await app.init();

    https.createServer(httpsOptions, server).listen(environment.app.port);
    https.createServer(httpsOptions, server).listen(environment.websocketPorts.units);
    https.createServer(httpsOptions, server).listen(environment.websocketPorts.items);
  } else {
    const app = await NestFactory.create(AppModule);
    app.useWebSocketAdapter(new WsAdapter(app));
    app.enableCors();
    await app.listen(environment.app.port);
  }
}
bootstrap();
1 Answers

You need to .create() a separate app for each port on which you listen for wss connections.

Related