Bird
Raised Fist0
NestJSframework~10 mins

WebSocket guards and pipes in NestJS - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to apply a guard to a WebSocket gateway method.

NestJS
import { UseGuards } from '@nestjs/common';
import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';
import { AuthGuard } from './auth.guard';

@WebSocketGateway()
export class ChatGateway {
  @[1](AuthGuard)
  @SubscribeMessage('message')
  handleMessage(client: any, payload: any) {
    return payload;
  }
}
Drag options to blanks, or click blank then click option'
AUsePipes
BUseFilters
CUseGuards
DUseInterceptors
Attempts:
3 left
💡 Hint
Common Mistakes
Using @UsePipes instead of @UseGuards
Forgetting to import the correct decorator
Applying the decorator to the class instead of the method
2fill in blank
medium

Complete the code to create a simple WebSocket pipe that transforms incoming data.

NestJS
import { PipeTransform, Injectable } from '@nestjs/common';

@Injectable()
export class [1] implements PipeTransform {
  transform(value: any) {
    return value.toUpperCase();
  }
}
Drag options to blanks, or click blank then click option'
AUppercasePipe
BValidationPipe
CAuthGuard
DLoggingPipe
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the pipe 'AuthGuard' which is for guards
Using 'ValidationPipe' which is a built-in pipe for validation
Not adding 'Pipe' suffix to the class name
3fill in blank
hard

Fix the error in applying a guard to a WebSocket gateway method.

NestJS
import { UseGuards } from '@nestjs/common';
import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';
import { AuthGuard } from './auth.guard';

@WebSocketGateway()
export class NotificationGateway {
  @UseGuards([1])
  @SubscribeMessage('notify')
  handleNotify(client: any, payload: any) {
    return payload;
  }
}
Drag options to blanks, or click blank then click option'
AAuthGuard()
BauthGuard
Cnew AuthGuard()
DAuthGuard
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses like a function call
Creating a new instance manually
Using a lowercase variable name instead of the class
4fill in blank
hard

Fill both blanks to apply a pipe and a guard to a WebSocket gateway method.

NestJS
import { UseGuards, UsePipes } from '@nestjs/common';
import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';
import { AuthGuard } from './auth.guard';
import { ValidationPipe } from './validation.pipe';

@WebSocketGateway()
export class MessageGateway {
  @[1](AuthGuard)
  @[2](ValidationPipe)
  @SubscribeMessage('send')
  handleSend(client: any, payload: any) {
    return payload;
  }
}
Drag options to blanks, or click blank then click option'
AUseGuards
BUseFilters
CUsePipes
DUseInterceptors
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up pipes and guards decorators
Using @UseFilters or @UseInterceptors incorrectly
Forgetting to import the decorators
5fill in blank
hard

Fill all three blanks to create a WebSocket pipe that validates and transforms data, then apply it with a guard.

NestJS
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
import { UseGuards, UsePipes } from '@nestjs/common';
import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';
import { AuthGuard } from './auth.guard';

@Injectable()
export class [1] implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    if (typeof value !== 'string') {
      throw new Error('Invalid data');
    }
    return value.trim();
  }
}

@WebSocketGateway()
export class DataGateway {
  @UseGuards([2])
  @UsePipes([3])
  @SubscribeMessage('data')
  handleData(client: any, payload: any) {
    return payload;
  }
}
Drag options to blanks, or click blank then click option'
ATrimPipe
BAuthGuard
DValidationPipe
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong class names for pipe or guard
Passing instances instead of classes to decorators
Not matching the pipe class name with the decorator argument

Practice

(1/5)
1. What is the main purpose of a WebSocket guard in a NestJS application?
easy
A. To control access and decide if a client can connect or send messages
B. To transform incoming message data before it reaches the handler
C. To log all WebSocket messages for debugging
D. To automatically retry failed WebSocket connections

Solution

  1. Step 1: Understand the role of guards

    Guards in NestJS are used to control access by allowing or denying client connections or message handling.
  2. Step 2: Differentiate guards from pipes

    Pipes transform or validate data, not control access, so they do not decide connection permissions.
  3. Final Answer:

    To control access and decide if a client can connect or send messages -> Option A
  4. Quick Check:

    Guards control access = A [OK]
Hint: Guards control access, pipes transform data [OK]
Common Mistakes:
  • Confusing guards with pipes
  • Thinking guards transform data
  • Assuming guards handle logging
2. Which of the following is the correct way to apply a guard to a WebSocket gateway method in NestJS?
easy
A. @UseGuards(MyGuard) on the gateway class
B. @UseGuards(MyGuard) on the gateway method
C. @UsePipes(MyGuard) on the gateway method
D. @UseFilters(MyGuard) on the gateway class

Solution

  1. Step 1: Recall decorator usage for guards

    Guards are applied using @UseGuards decorator either on the class or method. Applying on method is valid and common.
  2. Step 2: Identify correct decorator and target

    @UseGuards is correct for guards; @UsePipes is for pipes, and @UseFilters is for exception filters.
  3. Final Answer:

    @UseGuards(MyGuard) on the gateway method -> Option B
  4. Quick Check:

    @UseGuards on method = A [OK]
Hint: Use @UseGuards for guards, not pipes or filters [OK]
Common Mistakes:
  • Using @UsePipes instead of @UseGuards for guards
  • Applying filters instead of guards
  • Applying decorators on wrong targets
3. Given this WebSocket gateway method with a pipe, what will happen if the incoming message payload is invalid?
@SubscribeMessage('msg')
@UsePipes(new ValidationPipe())
handleMessage(@MessageBody() data: CreateDto) {
  return 'Received';
}
medium
A. The server crashes due to invalid data
B. The message is accepted without validation
C. The message is rejected and an error is sent back to the client
D. The message is transformed but still processed

Solution

  1. Step 1: Understand ValidationPipe behavior

    ValidationPipe checks incoming data and rejects it if invalid, sending an error response.
  2. Step 2: Analyze the method setup

    The method uses @UsePipes with ValidationPipe, so invalid data triggers rejection, not acceptance or crash.
  3. Final Answer:

    The message is rejected and an error is sent back to the client -> Option C
  4. Quick Check:

    ValidationPipe rejects invalid data = C [OK]
Hint: ValidationPipe rejects invalid data automatically [OK]
Common Mistakes:
  • Assuming invalid data is accepted
  • Thinking server crashes on invalid data
  • Confusing transformation with acceptance
4. Identify the error in this WebSocket gateway code snippet:
@SubscribeMessage('chat')
@UseGuards(AuthGuard)
@UsePipes(new ParseIntPipe())
handleChat(@MessageBody() data: string) {
  return data;
}
medium
A. handleChat method must return a Promise
B. AuthGuard cannot be used with WebSocket gateways
C. @UsePipes must be placed before @UseGuards
D. ParseIntPipe cannot parse a string directly without conversion

Solution

  1. Step 1: Check pipe compatibility with data type

    ParseIntPipe expects a value that can be parsed to integer, but data is a string that may not convert properly.
  2. Step 2: Validate other decorator usage

    AuthGuard is valid for WebSocket guards, and decorator order does not cause error here. Returning Promise is optional.
  3. Final Answer:

    ParseIntPipe cannot parse a string directly without conversion -> Option D
  4. Quick Check:

    ParseIntPipe needs numeric input = D [OK]
Hint: Pipes must match expected input types [OK]
Common Mistakes:
  • Assuming guards can't be used on WebSocket
  • Thinking decorator order always matters
  • Believing return type must be Promise
5. You want to ensure only authenticated users can send messages and that the message payload is a valid JSON object with a 'text' property. Which combination of guard and pipe setup is best in a NestJS WebSocket gateway?
hard
A. Use @UseGuards(AuthGuard) to check authentication and @UsePipes(ValidationPipe) with a DTO validating 'text' property
B. Use @UsePipes(AuthGuard) to check authentication and @UseGuards(ValidationPipe) for payload validation
C. Use @UseGuards(AuthGuard) only, and validate payload manually inside the handler
D. Use @UsePipes(ValidationPipe) only, assuming it checks authentication too

Solution

  1. Step 1: Assign correct roles to guard and pipe

    Guards handle authentication and authorization, so AuthGuard should be used as a guard.
  2. Step 2: Use ValidationPipe with DTO for payload validation

    ValidationPipe validates and transforms incoming data using a DTO that checks the 'text' property.
  3. Step 3: Evaluate other options

    Swapping guards and pipes misuses decorators; using guards only requires manual payload validation lacking automation; using pipes only misses authentication checks.
  4. Final Answer:

    Use @UseGuards(AuthGuard) to check authentication and @UsePipes(ValidationPipe) with a DTO validating 'text' property -> Option A
  5. Quick Check:

    Guard for auth + Pipe for validation = B [OK]
Hint: Guards for auth, pipes for data validation [OK]
Common Mistakes:
  • Swapping guards and pipes roles
  • Skipping automatic validation
  • Assuming pipes handle authentication
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