Bird
Raised Fist0
NestJSframework~20 mins

Why interceptors add cross-cutting logic in NestJS - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Interceptor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
What is the main purpose of interceptors in NestJS?
Interceptors in NestJS are often used to add cross-cutting logic. What does this mean in practice?
AThey allow you to run code before and after method execution, affecting multiple parts of the app without changing each method.
BThey replace the main logic of a controller method with a new implementation.
CThey only handle errors thrown by controller methods.
DThey are used to define database models and schemas.
Attempts:
2 left
💡 Hint
Think about how interceptors can wrap around method calls to add shared behavior.
❓ component_behavior
intermediate
2:00remaining
How does an interceptor modify the response in NestJS?
Given an interceptor that logs the time taken by a method, what will be the output behavior?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const start = Date.now();
    return next.handle().pipe(
      tap(() => console.log(`Execution time: ${Date.now() - start}ms`))
    );
  }
}
AThe interceptor blocks the response and only logs the time without returning anything.
BThe interceptor changes the response to include the execution time as a new field.
CThe interceptor logs the time before the method starts and returns an error.
DThe interceptor logs the execution time after the method completes, then returns the original response unchanged.
Attempts:
2 left
💡 Hint
Look at when the tap operator runs in the observable pipeline.
❓ lifecycle
advanced
1:30remaining
When is the intercept method called in the NestJS request lifecycle?
At what point does the intercept method of a NestJS interceptor execute relative to controller method execution?
AOnly after the controller method has completed and sent the response.
BBefore the controller method is called and after it returns, wrapping the method execution.
COnly before the controller method is called, without access to the response.
DOnly when an exception is thrown inside the controller method.
Attempts:
2 left
💡 Hint
Interceptors wrap around method calls like a sandwich.
📝 Syntax
advanced
2:30remaining
Which interceptor code correctly adds a header to the HTTP response?
Choose the correct NestJS interceptor code that adds a custom header 'X-Custom' with value 'Hello' to the response.
A
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class HeaderInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const response = context.switchToHttp().getResponse();
    response.setHeader('X-Custom', 'Hello');
    return next.handle();
  }
}
B
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class HeaderInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const response = context.getResponse();
    response.headers['X-Custom'] = 'Hello';
    return next.handle();
  }
}
C
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class HeaderInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const response = context.switchToHttp().getResponse();
    response.header('X-Custom', 'Hello');
    return next.handle();
  }
}
D
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class HeaderInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const response = context.switchToHttp().getResponse();
    response.setHeaders({'X-Custom': 'Hello'});
    return next.handle();
  }
}
Attempts:
2 left
💡 Hint
Check the correct method name to set a single header on the response object.
🔧 Debug
expert
3:00remaining
Why does this interceptor fail to log execution time?
Consider this interceptor code. It is supposed to log execution time but logs nothing. Why?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class SilentInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const start = Date.now();
    next.handle().subscribe(() => {
      console.log(`Execution time: ${Date.now() - start}ms`);
    });
    return next.handle();
  }
}
AThe interceptor returns next.handle() before the subscription logs, so the log never executes.
BThe console.log is inside subscribe but next.handle() is not subscribed properly, so it never runs.
CThe interceptor should use tap operator instead of subscribe to log side effects correctly.
DCalling next.handle() twice causes the observable to run twice, but the first subscription logs nothing because it is not awaited.
Attempts:
2 left
💡 Hint
Think about how RxJS observables work and how side effects should be handled.

Practice

(1/5)
1. What is the main reason to use interceptors in NestJS?
Interceptors help to add logic that applies to many parts of the app without repeating code. Why is this useful?
easy
A. They add shared logic before and after main code, like logging or timing.
B. They replace controllers to handle HTTP requests directly.
C. They store data permanently in the database.
D. They generate frontend UI components automatically.

Solution

  1. Step 1: Understand the role of interceptors

    Interceptors run code before and after the main handler, allowing shared tasks like logging or error handling.
  2. Step 2: Compare with other options

    Controllers handle requests, databases store data, and UI components are unrelated to interceptors.
  3. Final Answer:

    They add shared logic before and after main code, like logging or timing. -> Option A
  4. Quick Check:

    Interceptors add shared logic = A [OK]
Hint: Interceptors wrap main code to add shared tasks [OK]
Common Mistakes:
  • Thinking interceptors handle HTTP requests directly
  • Confusing interceptors with database or UI roles
  • Assuming interceptors replace controllers
2. Which of the following is the correct way to implement an interceptor in NestJS?
easy
A. Implement the NestInterceptor interface and define the intercept() method.
B. Create a class with a handle() method and decorate it with @Controller().
C. Use @Injectable() on a service without any methods.
D. Write a function that returns a promise without any interface.

Solution

  1. Step 1: Recall NestJS interceptor pattern

    Interceptors must implement the NestInterceptor interface and define the intercept() method.
  2. Step 2: Check other options

    Controllers use @Controller() and handle() is not an interceptor method; services need methods; plain functions lack interface.
  3. Final Answer:

    Implement the NestInterceptor interface and define the intercept() method. -> Option A
  4. Quick Check:

    Interceptor interface + intercept() = B [OK]
Hint: Interceptors always implement NestInterceptor with intercept() [OK]
Common Mistakes:
  • Confusing interceptors with controllers or services
  • Missing the intercept() method
  • Not using the NestInterceptor interface
3. Given this interceptor code snippet:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log('Before handler');
    return next.handle().pipe(
      tap(() => console.log('After handler'))
    );
  }
}

What will be printed to the console when a request is handled?
medium
A. Only After handler
B. Before handler, then After handler
C. Only Before handler
D. No output printed

Solution

  1. Step 1: Analyze the intercept method flow

    The interceptor logs 'Before handler' immediately, then calls next.handle() which runs the main handler.
  2. Step 2: Understand the tap operator

    The tap operator runs after the main handler completes, logging 'After handler'.
  3. Final Answer:

    Before handler, then After handler -> Option B
  4. Quick Check:

    Logs before and after handler = C [OK]
Hint: Logs before then after main handler due to tap() [OK]
Common Mistakes:
  • Thinking only one log prints
  • Confusing order of logs
  • Ignoring the tap() operator effect
4. You wrote this interceptor but it does not log anything:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class SilentInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log('Intercepted');
    next.handle();
  }
}

What is the problem?
medium
A. The import statements are incorrect.
B. The console.log statement is after next.handle(), so it never runs.
C. The class is missing the @Controller() decorator.
D. The intercept method does not return the observable from next.handle().

Solution

  1. Step 1: Check the intercept method return

    The intercept method must return the observable from next.handle() to continue the request flow.
  2. Step 2: Identify missing return

    Here, next.handle() is called but its result is not returned, so the request does not proceed and logs may not appear.
  3. Final Answer:

    The intercept method does not return the observable from next.handle(). -> Option D
  4. Quick Check:

    Missing return next.handle() = D [OK]
Hint: Always return next.handle() observable in intercept() [OK]
Common Mistakes:
  • Forgetting to return next.handle()
  • Misplacing console.log after next.handle()
  • Confusing decorators for interceptors
5. You want to measure the time taken by any request handler in your NestJS app. Which interceptor approach correctly adds this cross-cutting timing logic?
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const start = Date.now();
    return next.handle().pipe(
      tap(() => {
        const elapsed = Date.now() - start;
        console.log(`Request took ${elapsed}ms`);
      })
    );
  }
}
hard
A. This interceptor logs time but does not call next.handle(), so no handler runs.
B. This interceptor measures time only before the handler, missing after completion.
C. This interceptor correctly measures time before and after the handler using tap().
D. This interceptor should use setTimeout instead of tap() to measure time.

Solution

  1. Step 1: Understand timing measurement

    The interceptor records start time before calling next.handle() and uses tap() to run code after the handler completes.
  2. Step 2: Confirm correct usage of RxJS tap()

    The tap() operator runs side effects after the observable emits, so it correctly logs elapsed time after the request finishes.
  3. Final Answer:

    This interceptor correctly measures time before and after the handler using tap(). -> Option C
  4. Quick Check:

    Timing with tap() after handler = A [OK]
Hint: Use tap() after next.handle() to measure elapsed time [OK]
Common Mistakes:
  • Measuring time only before handler
  • Not returning next.handle() observable
  • Using setTimeout instead of RxJS operators
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard