Bird
0
0

Given this NestJS controller snippet, what will be the output when a logged-in user accesses /profile?

medium📝 component behavior Q13 of 15
NestJS - Authentication
Given this NestJS controller snippet, what will be the output when a logged-in user accesses /profile?
import { Controller, Get, Req } from '@nestjs/common';

@Controller()
export class AppController {
  @Get('profile')
  getProfile(@Req() req) {
    if (req.session.user) {
      return `Hello, ${req.session.user.name}`;
    } else {
      return 'Not logged in';
    }
  }
}
A"Hello, undefined" if user exists but name is missing
B"Not logged in" always
CThrows an error because req.session is undefined
D"Hello, Alice" if req.session.user.name is 'Alice'
Step-by-Step Solution
Solution:
  1. Step 1: Check session user existence

    The code checks if req.session.user exists to decide output.
  2. Step 2: Understand output when user exists

    If user exists with name 'Alice', it returns "Hello, Alice" string.
  3. Final Answer:

    "Hello, Alice" if req.session.user.name is 'Alice' -> Option D
  4. Quick Check:

    Session user present returns greeting = A [OK]
Quick Trick: If session user exists, greet by name; else say not logged in [OK]
Common Mistakes:
  • Assuming req.session is always undefined
  • Ignoring the user existence check
  • Confusing output strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes