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?
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.
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> {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With