coler-j
coler-j

Reputation: 2129

Global Headers for all Controllers (nestJs swagger)

Is there a way to globally add required headers to all endpoints / controllers in NestJS?

There is a controller bound decorator @ApiHeader. Is there a way to apply this to all endpoints?

Upvotes: 13

Views: 8760

Answers (3)

Gvs Akhil
Gvs Akhil

Reputation: 2608

In 2023, you can add global headers in main.ts

const config = new DocumentBuilder()
    .setTitle('Kuber apis')
    .setVersion('1.0')
    .addBearerAuth(
      { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', in: 'header' },
      'JWT',
    )
    .addGlobalParameters({
      name: 'assetId',
      in: 'header',
    })
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

It shows up in every routeenter image description here

Upvotes: 2

Dmytro Kobyzskyi
Dmytro Kobyzskyi

Reputation: 141

You can use DocumentBuilder.addGlobalParameters method.

Unfortunately, it's not described in the documentation, but here is my example:

SwaggerModule.setup(
    'docs',
    application, // your NestJS application created by NestFactory.create
    SwaggerModule.createDocument(
      application,
      new DocumentBuilder()
        .setTitle('My application')
        .addGlobalParameters({
          in: 'header',
          required: false,
          name: 'x-global-header',
          schema: {
            example: 'some value',
          },
        })
        .build(),
    ),
  );

Upvotes: 12

coler-j
coler-j

Reputation: 2129

Shortest way I have found is to do the following:

export function Headers() {
  return applyDecorators(
    ApiHeader({
      name: 'header1',
      description: "description"
    }),
    ApiHeader({
      name: 'header2',
      description: "description"
    }),
    ApiHeader({
      name: 'header3',
      description: "description"
    })
  );
}
@Headers()
@Controller('some-controller')
export class ContactsController {}

Upvotes: 17

Related Questions