Search code examples
browserswaggernestjsswagger-ui

Nestjs/swagger open browser automatically like in REACT


I'd like my Nestjs/swagger application to start up as soon as bootstrap is finished

Initially I thought of using the callback of

async function bootstrap(): Promise<void> {
    console.clear();
    console.log("Starting and validating");

    const app = await NestFactory.create<NestExpressApplication>(AppModule, {
        cors: true,
    });

    await app.listen(PORT, () => someOpenBrowserFuncion("/docs")`));
}
bootstrap();

But I didn't find anything like that, so I thought

When we start a REACT app, as soon as it is compiled, it opens the default browser automatically. and This option can be disabled with the following command:

"scripts": {
  "start": "env BROWSER=none react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
},

Is there a similar function in the Nestjs/swagger framework?

"scripts": {
  "build": "nest build",
  "dev": "nest start --watch",
  "start": "env BROWSER=true nest start",
  "production": "node dist/main",

},

Or some configuration to launch browser on certain endpoint?


Solution

  • You can install a npm package cross-env : npm install cross-env

    And update this command in the package.json file under 'scripts';

    "start": "cross-env BROWSER='chrome' nest start"
    

    BROWSER is an environment variable, and you can use the cross-env package to properly handle it.

    Linux:
     BROWSER='google-chrome-stable'
    Windows:
     BROWSER='chrome'
    OS X:
     BROWSER='google chrome'
    

    If these don't work, you can update the script:

    Windows:
    "start": "start http://localhost:3000 & nest start"
    Mac:
    "start": "open http://localhost:3000 && nest start"
    Linux:
    "start": "xdg-open http://localhost:3000 && nest start"
    

    You can change your own port number.