Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Headers for all Controllers (nestJs swagger)

Tags:

swagger

nestjs

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?

like image 573
coler-j Avatar asked Jan 22 '26 02:01

coler-j


2 Answers

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 {}
like image 196
coler-j Avatar answered Jan 25 '26 01:01

coler-j


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(),
    ),
  );
like image 30
Dmytro Kobyzskyi Avatar answered Jan 25 '26 00:01

Dmytro Kobyzskyi