0
0
NestJSframework~8 mins

Role-based authorization in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Role-based authorization
MEDIUM IMPACT
Role-based authorization affects server response time and client perceived latency by controlling access before processing requests fully.
Checking user roles to authorize access to API endpoints
NestJS
canActivate(context: ExecutionContext) {
  const request = context.switchToHttp().getRequest();
  const userRoles = request.user.roles; // roles included in JWT token
  if (!userRoles.includes('admin')) {
    throw new ForbiddenException('Access denied');
  }
  return true;
}
Using roles embedded in JWT avoids extra database calls, speeding up authorization checks.
📈 Performance GainReduces request blocking by 50-100ms, improving INP and server throughput.
Checking user roles to authorize access to API endpoints
NestJS
async canActivate(context: ExecutionContext) {
  const request = context.switchToHttp().getRequest();
  const user = await this.userService.findUserById(request.user.id);
  if (!user.roles.includes('admin')) {
    throw new ForbiddenException('Access denied');
  }
  return true;
}
Fetching user roles from database on every request causes extra network calls and delays response.
📉 Performance CostBlocks request processing for 50-100ms per call, increasing INP and server load.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Fetching roles from DB on each request000[X] Bad
Using roles from JWT token000[OK] Good
Rendering Pipeline
Role-based authorization runs on the server before sending response, affecting server processing time and thus interaction responsiveness.
Server Request Processing
Response Generation
⚠️ BottleneckExtra database calls during authorization increase server processing time.
Core Web Vital Affected
INP
Role-based authorization affects server response time and client perceived latency by controlling access before processing requests fully.
Optimization Tips
1Avoid database calls for role checks on every request to reduce server blocking.
2Embed user roles in JWT tokens or cache them to speed up authorization.
3Fast authorization improves interaction responsiveness and reduces server load.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance downside of fetching user roles from the database on every request?
AIt improves client-side rendering speed.
BIt increases server response time and delays user interaction.
CIt reduces server memory usage.
DIt decreases network latency.
DevTools: Network and Performance
How to check: Use Network panel to measure API response times; use Performance panel to check server response blocking time.
What to look for: Look for long server response times caused by authorization delays; shorter times indicate better performance.