azureswaggerazure-functionsnestjsnestjs-swagger

Configure swagger with Nestjs + Azure functions


I am trying to develop my nestjs using azure functions following this article: https://trilon.io/blog/deploy-nestjs-azure-functions

I have configured Swagger in my application as follows:

...
const options = new DocumentBuilder()
    .setTitle('App title')
    .setDescription('App description')
    .setVersion('1.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
      },
      'authorization',
    )
    .addTag('freight')
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('swagger', app, document);
...

When I run the app in development, I can access my swagger UI by navigating to /swagger, however when I run npm run build && func host start, I receive 500 error, which also happens when I hit a non-existing route.

All other routes that are registered in the application work as expected.


Solution

  • Nestjs has a module you need to load for this. nestjs-openapi

    Next you will need to specify a few configuration items.

    Note: Main.ts is not used at all.

    Sync ports with:

    func host start --port 3000
    

    !! Use the app instance within the main.azure.ts. Example assumes global prefix defined above the code below.

    ...
    //config
    const config = new DocumentBuilder()
    .setTitle('My Title')
    .setDescription('My Description')
    .setVersion('1.0')
    .setBasePath('api-docs')
    .build();
    
    const document = SwaggerModule.createDocument(app, config);
    
    SwaggerModule.setup('api-docs', app, document, {
      useGlobalPrefix: true,
    });
    
    // order matters here. 
    app.init() 
    // port that is used for swagger ui. Sync with Az Fx. 
    app.listen(3000)
    

    Now you can route to localhost:3000/{global_prefix}/api-docs to load swagger ui.