0
0
NestJSframework~8 mins

Custom validation decorators in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Custom validation decorators
MEDIUM IMPACT
This affects the runtime validation speed during request processing and can impact server response time and user experience.
Validating user input with custom decorators
NestJS
import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';

@ValidatorConstraint({ async: true })
export class IsUniqueEmailConstraint implements ValidatorConstraintInterface {
  private cache = new Set<string>();

  async validate(email: string) {
    if (this.cache.has(email)) return true; // Cached result
    // Simulate fast async check
    const isUnique = email !== 'taken@example.com';
    if (isUnique) this.cache.add(email);
    return isUnique;
  }
}

export function IsUniqueEmail(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsUniqueEmailConstraint,
      async: true
    });
  };
}
Caches validation results to avoid repeated slow checks, reducing validation time and improving request responsiveness.
📈 Performance GainReduces average validation time from 1000ms to near 0ms on repeated inputs, improving INP significantly.
Validating user input with custom decorators
NestJS
import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';

@ValidatorConstraint({ async: true })
export class IsUniqueEmailConstraint implements ValidatorConstraintInterface {
  validate(email: string) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(email !== 'taken@example.com');
      }, 1000); // Simulates slow async check
    });
  }
}

export function IsUniqueEmail(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsUniqueEmailConstraint,
      async: true
    });
  };
}
The validation runs a slow asynchronous check with a 1-second delay on every input, blocking request processing and increasing response time.
📉 Performance CostBlocks request processing for 1000ms per validation, increasing INP and server response time.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Slow async validation with delayN/A (server-side)N/AN/A[X] Bad
Cached fast validation logicN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Custom validation decorators run during request validation before controller logic executes, affecting server-side processing time and response delivery.
Request Processing
Validation Logic
Response Generation
⚠️ BottleneckValidation Logic stage when decorators perform slow or blocking operations
Core Web Vital Affected
INP
This affects the runtime validation speed during request processing and can impact server response time and user experience.
Optimization Tips
1Avoid long blocking operations inside custom validation decorators.
2Cache validation results when possible to speed up repeated checks.
3Keep validation logic lightweight to improve server response and user input responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using slow asynchronous operations inside custom validation decorators?
AThey block request processing and increase server response time
BThey increase browser paint time
CThey cause layout shifts on the page
DThey increase CSS selector complexity
DevTools: Network and Performance panels
How to check: Use the Network panel to measure request duration and the Performance panel to profile server response time and validation delays.
What to look for: Look for long request times and blocking periods during validation phase indicating slow custom decorators.