Discover how sessions keep users logged in effortlessly and safely!
Why Session-based authentication in NestJS? - Purpose & Use Cases
Imagine building a website where users must log in to see their personal info. Without sessions, you have to check their username and password on every page manually.
Manually checking login details on every request is slow and risky. You might forget to check, causing security holes. Also, users would have to log in again and again, which is frustrating.
Session-based authentication stores user login info on the server and remembers it with a session ID in the browser. This way, users stay logged in securely without re-entering credentials each time.
if (req.body.username === 'user' && req.body.password === 'pass') { /* allow access */ } else { /* deny */ }
req.session.user = { id: 1, name: 'user' }; // user stays logged in across requestsIt enables smooth, secure user experiences where login status is remembered automatically across many pages.
Think of online shopping sites that keep you logged in while you browse products, add to cart, and checkout without asking for your password again.
Manual login checks on every page are slow and error-prone.
Sessions store login info safely on the server.
Users enjoy seamless, secure access across the site.
Practice
Solution
Step 1: Understand session-based authentication
Session-based authentication stores user info on the server to track login status across requests.Step 2: Compare options with session concept
Only To keep user login information on the server for tracking user sessions describes storing user login info on the server, which matches session-based authentication.Final Answer:
To keep user login information on the server for tracking user sessions -> Option AQuick Check:
Session stores user info on server = C [OK]
- Confusing sessions with token storage
- Thinking sessions store passwords in browser
- Believing credentials are sent every request without storage
Solution
Step 1: Identify correct package for session in NestJS
The official session support in NestJS is provided by '@nestjs/session'.Step 2: Check import statements
Only import { SessionModule } from '@nestjs/session'; imports SessionModule from '@nestjs/session', which is correct syntax.Final Answer:
import { SessionModule } from '@nestjs/session'; -> Option AQuick Check:
SessionModule from '@nestjs/session' = D [OK]
- Importing SessionModule from '@nestjs/common'
- Confusing express-session with NestJS module import
- Using incorrect package names
/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';
}
}
}Solution
Step 1: Check session user existence
The code checks if req.session.user exists to decide output.Step 2: Understand output when user exists
If user exists with name 'Alice', it returns "Hello, Alice" string.Final Answer:
"Hello, Alice" if req.session.user.name is 'Alice' -> Option DQuick Check:
Session user present returns greeting = A [OK]
- Assuming req.session is always undefined
- Ignoring the user existence check
- Confusing output strings
import { Module } from '@nestjs/common';
import { SessionModule } from '@nestjs/session';
@Module({
imports: [
SessionModule.forRoot({
secret: 'mySecret',
resave: false,
saveUninitialized: true,
}),
],
})
export class AppModule {}Solution
Step 1: Review SessionModule options
In '@nestjs/session', options like 'resave' and 'saveUninitialized' are not valid; they belong to express-session directly.Step 2: Identify correct option usage
SessionModule expects options like 'secret' and 'cookie', but not 'resave' or 'saveUninitialized'.Final Answer:
'resave' and 'saveUninitialized' are not valid options for SessionModule -> Option CQuick Check:
Invalid options in SessionModule config = B [OK]
- Adding express-session options directly to SessionModule
- Confusing 'forRoot' with 'register'
- Ignoring required cookie config
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?
}
}Solution
Step 1: Check if user is logged in via session
We verify if req.session.user exists; if not, deny access with 401 status.Step 2: Return welcome message if user exists
If user exists, send a welcome message with their name.Final Answer:
if (!req.session.user) { return res.status(401).send('Unauthorized'); } return res.send('Welcome ' + req.session.user.name); -> Option BQuick Check:
Check session user, deny if missing = A [OK]
- Throwing errors instead of sending HTTP response
- Checking only if req.session exists, not user
- Reversing logic for authorization
Ready to prove it?
Pass the test and this pattern moves unknown
