Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set request body size limit on NestJs for single controller

I want to increase request body size limit for a single route, let's say only for route /uploads, and keep the rest to be the default.

I know you can set globally using

app.use(json({ limit: '50mb' }));

Or, when in pure ExpressJS you can use

router.use('/uploads', express.json({ limit: '50MB' }));

But in NestJS there's only a global app and controller classes. E.g.

@Controller('uploads')
export class UploadController {
  constructor() {}

  @Post()
  create(...): Promise<any> {
    ...
  }
}

Where to set the limit for this controller?

like image 986
Myles Avatar asked Sep 18 '25 07:09

Myles


2 Answers

Actually, it is possible to increase the size limit for one route in NestJS, like this:

     app.use('/uploads', json({ limit: '50mb' }));
     app.use(json({ limit: '100kb' }));

Second statement is needed for resetting the limit for all other routes.

like image 198
binici Avatar answered Sep 19 '25 22:09

binici


You can use guard for this.

import {
  Injectable,
  CanActivate,
  ExecutionContext,
  applyDecorators,
  UseGuards,
  SetMetadata,
} from '@nestjs/common'
import { Reflector } from '@nestjs/core'

@Injectable()
export class LimitGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest()
    const limit = this.reflector.get<string[]>('limit', context.getHandler())
    return limit > request.socket.bytesRead
  }
}

export const Limit = (limit: number) =>
  applyDecorators(UseGuards(LimitGuard), SetMetadata('limit', limit))

and, in your controller

  @Limit(1024 * 1024)
  @Post('your-path')
  async limitedMethod(): Promise<string> {
    // ...
  }
like image 30
pismenskiy Avatar answered Sep 19 '25 23:09

pismenskiy