Bird
Raised Fist0
NestJSframework~20 mins

Logging interceptor in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Logging Interceptor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
1:30remaining
Output of a simple NestJS logging interceptor
Given the following NestJS logging interceptor code, what will be logged when a controller method returns 'Hello World'?
NestJS
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 execution');
    return next.handle().pipe(
      tap(() => console.log('After handler execution'))
    );
  }
}
ADoes not log anything
BLogs only 'Before handler execution' before the method
CLogs only 'After handler execution' after the method
DLogs 'Before handler execution' before the method and 'After handler execution' after the method
Attempts:
2 left
💡 Hint
Think about when the tap operator runs in an RxJS observable pipeline.
🧠 Conceptual
intermediate
1:00remaining
Purpose of a logging interceptor in NestJS
What is the main purpose of using a logging interceptor in a NestJS application?
ATo modify the response body before sending it to the client
BTo log details about incoming requests and outgoing responses centrally
CTo handle exceptions thrown by controller methods
DTo authenticate users before accessing routes
Attempts:
2 left
💡 Hint
Think about what interceptors can do with requests and responses.
❓ Configuration
advanced
1:30remaining
Correct way to apply a global logging interceptor in NestJS
Which code snippet correctly applies a logging interceptor globally in a NestJS application?
NestJS
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { LoggingInterceptor } from './logging.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // Apply interceptor here
  await app.listen(3000);
}
bootstrap();
Aapp.useGlobalInterceptors(new LoggingInterceptor());
Bapp.useGlobalInterceptor(new LoggingInterceptor());
Capp.applyGlobalInterceptors(new LoggingInterceptor());
Dapp.useInterceptorGlobally(new LoggingInterceptor());
Attempts:
2 left
💡 Hint
Check the exact method name for applying global interceptors in NestJS.
❓ Troubleshoot
advanced
2:00remaining
Why does the logging interceptor not log after handler execution?
A developer notices that their NestJS logging interceptor logs the message before the handler but never logs the message after the handler execution. What is the most likely cause?
AThe controller method returns a Promise instead of an Observable
BThe tap operator is missing in the interceptor's pipe
CThe interceptor forgot to return next.handle() observable
DThe interceptor is not decorated with @Injectable()
Attempts:
2 left
💡 Hint
Check the return statement in the intercept method.
🔀 Workflow
expert
2:30remaining
Order of execution in multiple NestJS interceptors
Given two global interceptors, LoggingInterceptor and TimingInterceptor, applied in this order: app.useGlobalInterceptors(new LoggingInterceptor(), new TimingInterceptor()); Which order will their 'before' and 'after' logs appear when a controller method is called?
ALoggingInterceptor before, TimingInterceptor before, controller runs, TimingInterceptor after, LoggingInterceptor after
BTimingInterceptor before, LoggingInterceptor before, controller runs, LoggingInterceptor after, TimingInterceptor after
CLoggingInterceptor before, TimingInterceptor before, controller runs, LoggingInterceptor after, TimingInterceptor after
DTimingInterceptor before, LoggingInterceptor before, controller runs, TimingInterceptor after, LoggingInterceptor after
Attempts:
2 left
💡 Hint
Think of interceptors like nested layers wrapping the controller method.

Practice

(1/5)
1. What is the main purpose of a LoggingInterceptor in a NestJS application?
easy
A. To manage user authentication and authorization
B. To handle database connections automatically
C. To log details about incoming requests and outgoing responses
D. To serve static files like images and CSS

Solution

  1. Step 1: Understand the role of interceptors

    Interceptors in NestJS run code before and after request handlers, often used for logging or modifying requests/responses.
  2. Step 2: Identify the purpose of LoggingInterceptor

    A LoggingInterceptor specifically tracks and logs request and response details for debugging and monitoring.
  3. Final Answer:

    To log details about incoming requests and outgoing responses -> Option C
  4. Quick Check:

    LoggingInterceptor = logs requests/responses [OK]
Hint: LoggingInterceptor logs request and response info [OK]
Common Mistakes:
  • Confusing interceptors with middleware
  • Thinking interceptors handle authentication
  • Assuming interceptors serve static files
2. Which of the following is the correct way to implement the intercept method in a NestJS LoggingInterceptor?
easy
A. intercept(context, next) { return next.handle(); }
B. intercept(context, next) { next.handle(); }
C. intercept(context) { return next.handle(); }
D. intercept(next) { return context.handle(); }

Solution

  1. Step 1: Recall the intercept method signature

    The intercept method receives two parameters: context and next. It must return next.handle() to continue the request lifecycle.
  2. Step 2: Check each option for correct syntax

    intercept(context, next) { return next.handle(); } correctly uses both parameters and returns next.handle(). Options A, C, and D either miss parameters or do not return the observable.
  3. Final Answer:

    intercept(context, next) { return next.handle(); } -> Option A
  4. Quick Check:

    intercept(context, next) returns next.handle() [OK]
Hint: intercept always returns next.handle() with both parameters [OK]
Common Mistakes:
  • Omitting return statement
  • Missing one of the parameters
  • Calling handle on wrong object
3. Given this LoggingInterceptor code snippet, what will be logged when a request is handled?
intercept(context, next) {
  const now = Date.now();
  return next.handle().pipe(
    tap(() => console.log(`Request took ${Date.now() - now}ms`))
  );
}
medium
A. Logs the time taken to process the request in milliseconds
B. Logs the request URL only
C. Logs the response body content
D. Logs an error message if the request fails

Solution

  1. Step 1: Analyze the timing logic

    The code records the current time before the request is handled, then logs the difference after the response is sent.
  2. Step 2: Understand the logged message

    The console.log outputs "Request took Xms" where X is the elapsed time in milliseconds.
  3. Final Answer:

    Logs the time taken to process the request in milliseconds -> Option A
  4. Quick Check:

    LoggingInterceptor measures request duration [OK]
Hint: Look for Date.now() difference to find elapsed time [OK]
Common Mistakes:
  • Assuming it logs request URL or body
  • Thinking it logs errors only
  • Ignoring the timing calculation
4. Identify the error in this LoggingInterceptor code:
intercept(context, next) {
  const now = Date.now();
  next.handle().pipe(
    tap(() => console.log(`Request took ${Date.now() - now}ms`))
  );
}
medium
A. tap operator is not imported
B. Incorrect use of Date.now()
C. Missing context parameter
D. Missing return statement before 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 lifecycle.
  2. Step 2: Identify missing return

    The code calls next.handle().pipe(...) but does not return it, so the request will not proceed properly.
  3. Final Answer:

    Missing return statement before next.handle() -> Option D
  4. Quick Check:

    intercept must return next.handle() observable [OK]
Hint: Always return next.handle() in intercept method [OK]
Common Mistakes:
  • Forgetting to return the observable
  • Misusing Date.now() for timing
  • Ignoring required parameters
5. You want to create a LoggingInterceptor that logs the request method, URL, and the time taken for each request. Which code snippet correctly implements this behavior?
hard
A. intercept(context, next) { const req = context.getRequest(); const now = Date.now(); next.handle().pipe( tap(() => console.log(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); }
B. intercept(context, next) { const req = context.switchToHttp().getRequest(); const now = Date.now(); return next.handle().pipe( tap(() => console.log(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); }
C. intercept(context, next) { const req = context.switchToHttp().getRequest(); const now = Date.now(); return next.handle().pipe( map(() => console.log(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); }
D. intercept(context, next) { const req = context.switchToHttp().getRequest(); const now = Date.now(); return next.handle().pipe( tap(() => console.error(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); }

Solution

  1. Step 1: Access request object correctly

    Use context.switchToHttp().getRequest() to get the HTTP request object in NestJS interceptors.
  2. Step 2: Use tap operator for side effects

    The tap operator is used to perform logging without altering the response stream. Using map or console.error is incorrect here.
  3. Final Answer:

    intercept(context, next) { const req = context.switchToHttp().getRequest(); const now = Date.now(); return next.handle().pipe( tap(() => console.log(`${req.method} ${req.url} - ${Date.now() - now}ms`)) ); } -> Option B
  4. Quick Check:

    Use switchToHttp(), tap, and return next.handle() [OK]
Hint: Use switchToHttp().getRequest() and tap for logging [OK]
Common Mistakes:
  • Not returning next.handle()
  • Using map instead of tap
  • Using console.error instead of console.log
  • Incorrect request object access
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