Session-based authentication is a method where the server creates a session for a user after login and stores session data. The client keeps a session ID cookie to identify the session on future requests.
Click to reveal answer
intermediate
How does NestJS handle sessions for authentication?
NestJS uses middleware like express-session to create and manage sessions. After login, session data is saved on the server, and a session cookie is sent to the client to maintain login state.
Click to reveal answer
beginner
What role does the cookie play in session-based authentication?
The cookie stores the session ID on the client side. It is sent automatically with each request to the server, allowing the server to find the matching session and verify the user's identity.
Click to reveal answer
intermediate
Why is it important to set 'httpOnly' and 'secure' flags on session cookies?
Setting 'httpOnly' prevents JavaScript access to cookies, reducing cross-site scripting risks. 'Secure' ensures cookies are sent only over HTTPS, protecting session data from being intercepted.
Click to reveal answer
intermediate
How do you protect routes in NestJS to allow only authenticated users with sessions?
You use guards like AuthGuard that check if the session exists and is valid before allowing access. If no valid session is found, the guard blocks the request or redirects to login.
Click to reveal answer
In session-based authentication, where is the session data stored?
AOn the server
BIn the client's local storage
CInside the cookie itself
DIn the URL parameters
✗ Incorrect
Session data is stored on the server. The client only holds a session ID in a cookie.
Which NestJS middleware is commonly used to manage sessions?
Acors
Bbody-parser
Chelmet
Dexpress-session
✗ Incorrect
express-session middleware is used to create and manage sessions in NestJS.
What does the 'httpOnly' flag on a cookie do?
APrevents JavaScript from accessing the cookie
BMakes the cookie accessible only on HTTP, not HTTPS
CAllows the cookie to be shared across domains
DEncrypts the cookie content
✗ Incorrect
'httpOnly' prevents JavaScript access to cookies, improving security.
How does the server identify a user in session-based authentication?
ABy decoding a JWT token
BBy checking the user's IP address
CBy reading the session ID from the cookie sent by the client
DBy reading user credentials from the request body
✗ Incorrect
The server uses the session ID from the cookie to find the user's session.
What happens if a user tries to access a protected route without a valid session in NestJS?
AThe user is granted access anyway
BThe request is blocked or redirected to login
CThe server creates a new session automatically
DThe server returns a 500 error
✗ Incorrect
Guards check for valid sessions and block or redirect unauthorized users.
Explain how session-based authentication works in NestJS from login to accessing protected routes.
Think about what happens step-by-step when a user logs in and then visits a page that needs login.
You got /6 concepts.
Describe the security best practices for session cookies in NestJS applications.
Focus on cookie flags and how they protect user sessions.
You got /5 concepts.
Practice
(1/5)
1. What is the main purpose of session-based authentication in NestJS?
easy
A. To keep user login information on the server for tracking user sessions
B. To store user passwords in the browser for quick access
C. To send user credentials with every request without storing them
D. To use tokens stored in local storage for authentication
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 A
Quick Check:
Session stores user info on server = C [OK]
Hint: Sessions store user info on server, not client [OK]
Common Mistakes:
Confusing sessions with token storage
Thinking sessions store passwords in browser
Believing credentials are sent every request without storage
2. Which of the following is the correct way to import session support in a NestJS module?
easy
A. import { SessionModule } from '@nestjs/session';
B. import { SessionModule } from '@nestjs/common';
C. import { SessionModule } from 'express-session';
D. import { SessionModule } from 'nestjs-session';
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 A
Quick Check:
SessionModule from '@nestjs/session' = D [OK]
Hint: SessionModule comes from '@nestjs/session' package [OK]
Common Mistakes:
Importing SessionModule from '@nestjs/common'
Confusing express-session with NestJS module import
Using incorrect package names
3. Given this NestJS controller snippet, what will be the output when a logged-in user accesses /profile?
A. "Hello, undefined" if user exists but name is missing
B. "Not logged in" always
C. Throws an error because req.session is undefined
D. "Hello, Alice" if req.session.user.name is 'Alice'
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 D
Quick Check:
Session user present returns greeting = A [OK]
Hint: 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
4. Identify the error in this NestJS session setup code:
import { Module } from '@nestjs/common';
import { SessionModule } from '@nestjs/session';
@Module({
imports: [
SessionModule.forRoot({
secret: 'mySecret',
resave: false,
saveUninitialized: true,
}),
],
})
export class AppModule {}
medium
A. Missing 'cookie' configuration inside forRoot options
B. The secret should be an environment variable, not a string literal
C. 'resave' and 'saveUninitialized' are not valid options for SessionModule
D. SessionModule.forRoot should be replaced with SessionModule.register
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 C
Quick Check:
Invalid options in SessionModule config = B [OK]
Hint: Check if options belong to NestJS SessionModule or express-session [OK]
Common Mistakes:
Adding express-session options directly to SessionModule
Confusing 'forRoot' with 'register'
Ignoring required cookie config
5. 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?
}
}
hard
A. if (req.session.user === undefined) { throw new Error('No session'); } return 'Welcome';
B. if (!req.session.user) { return res.status(401).send('Unauthorized'); } return res.send('Welcome ' + req.session.user.name);
C. if (!req.session) { return 'Please login'; } return 'Dashboard';
D. if (req.session.user) { return 'Unauthorized'; } else { return 'Welcome'; }
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 B
Quick Check:
Check session user, deny if missing = A [OK]
Hint: 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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.