Search code examples
expressnestjs

What is the NestJS equivalent to expressjs server.on('listening', ...)


I try to port an application to NestJS but I have not found the 'NestJS way' of listening for a successful server connection.

From the old app

server.on('listening', async function (): Promise<void> {
    ...
});

In the new app I currently have placed some code after the listen call...

await app.listen(options.port);
// do anything when the server listens

...but that's not the same as an event handler. I don't know if 'listen' events can come multiple times (reconnects?!) but there has to be a way to listen for that event for example decoupled in other code parts?!

In the docs I have found the onApplicationBootstrap() lifecycle hook method but that's called "once all modules have been initialized, but before listening for connections."

I thought about getting the HttpAdapter or Server ask if it is instanceof ExpressAdapter and do something like .on('listen',... when I find the right instance, but at least in the @types I haven't found the right way of doing this and it smells like a hack.

Can someone please point me to the place in the docs or show me how to do this preferably in an adapter-agnostic NestJS way? Seems like I search for the wrong things.


Solution

  • It's not the getHttpAdapter but getHttpServer!

    The important parts are

    const app = await NestFactory.create<NestExpressApplication>(AppModule);
    const serverInstance = app.getHttpServer() as Server;
    serverInstance.on('listening', ...);
    

    Unfortunately app.getHttpServer returns an object of type any. app.listen returns the same instance but the type is Server.