Bird
0
0

You want to protect a NestJS route so only logged-in users with a session can access it. Which approach correctly checks the session and denies access if no user is logged in?

hard📝 Application Q15 of 15
NestJS - Authentication
You want to protect a NestJS route so only logged-in users with a session can access it. Which approach correctly checks the session and denies access if no user is logged in?
import { Controller, Get, Req, Res } from '@nestjs/common';
import { Response, Request } from 'express';

@Controller()
export class AppController {
  @Get('dashboard')
  dashboard(@Req() req: Request, @Res() res: Response) {
    // What should go here?
  }
}
Aif (req.session.user === undefined) { throw new Error('No session'); } return 'Welcome';
Bif (!req.session.user) { return res.status(401).send('Unauthorized'); } return res.send('Welcome ' + req.session.user.name);
Cif (!req.session) { return 'Please login'; } return 'Dashboard';
Dif (req.session.user) { return 'Unauthorized'; } else { return 'Welcome'; }
Step-by-Step Solution
Solution:
  1. Step 1: Check if user is logged in via session

    We verify if req.session.user exists; if not, deny access with 401 status.
  2. Step 2: Return welcome message if user exists

    If user exists, send a welcome message with their name.
  3. Final Answer:

    if (!req.session.user) { return res.status(401).send('Unauthorized'); } return res.send('Welcome ' + req.session.user.name); -> Option B
  4. Quick Check:

    Check session user, deny if missing = A [OK]
Quick Trick: Return 401 if no session user, else welcome [OK]
Common Mistakes:
  • Throwing errors instead of sending HTTP response
  • Checking only if req.session exists, not user
  • Reversing logic for authorization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes