Bird
Raised Fist0
NestJSframework~5 mins

Session-based authentication in NestJS

Choose your learning style10 modes available
Introduction

Session-based authentication helps keep users logged in by saving their login info on the server. It makes sure only the right people can access protected parts of your app.

You want users to stay logged in while they browse your site.
You need to protect pages so only logged-in users can see them.
You want to store user info safely on the server, not in the browser.
You want to easily log users out by clearing their session.
You want to track user activity during their visit.
Syntax
NestJS
import { Module } from '@nestjs/common';
import * as cookieParser from 'cookie-parser';
import * as session from 'express-session';

@Module({
  // Session configured in bootstrap
})
export class AppModule {}

// In main.ts or bootstrap:
/*
app.use(cookieParser());
app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
}));
*/

// In your controller
import { Controller, Get, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';

@Controller()
export class AuthController {
  @Get('login')
  login(@Req() req: Request, @Res() res: Response) {
    req.session.user = { id: 1, name: 'Alice' };
    res.send('Logged in');
  }

  @Get('profile')
  profile(@Req() req: Request) {
    if (req.session.user) {
      return req.session.user;
    }
    return 'Not logged in';
  }
}

Configure cookie-parser and express-session middleware in the NestJS bootstrap() function.

Store user info in req.session to keep it across requests.

Examples
Saves user info in the session after login.
NestJS
req.session.user = { id: 1, name: 'Alice' };
Checks if a user is logged in by looking for session data.
NestJS
if (req.session.user) {
  // user is logged in
}
Logs out the user by clearing their session.
NestJS
req.session.destroy(() => {
  // session cleared, user logged out
});
Sample Program

This simple NestJS app uses session-based authentication. When you visit /login, it saves user info in the session. Visiting /profile shows the user info if logged in. Visiting /logout clears the session.

NestJS
import { Module, Controller, Get, Req, Res } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import * as cookieParser from 'cookie-parser';
import * as session from 'express-session';
import { Request, Response } from 'express';

@Controller()
class AuthController {
  @Get('login')
  login(@Req() req: Request, @Res() res: Response) {
    req.session.user = { id: 1, name: 'Alice' };
    res.send('Logged in');
  }

  @Get('profile')
  profile(@Req() req: Request) {
    if (req.session.user) {
      return req.session.user;
    }
    return 'Not logged in';
  }

  @Get('logout')
  logout(@Req() req: Request, @Res() res: Response) {
    req.session.destroy((err) => {
      if (err) {
        return res.status(500).send('Error logging out');
      }
      res.send('Logged out');
    });
  }
}

@Module({
  controllers: [AuthController],
})
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(cookieParser());
  app.use(session({
    secret: 'my-secret-key',
    resave: false,
    saveUninitialized: false,
  }));
  await app.listen(3000);
}
bootstrap();
OutputSuccess
Important Notes

Sessions store data on the server, so users can't change their login info directly.

Always use a strong secret key to keep sessions secure.

Session data is temporary and usually expires after some time or when the user logs out.

Summary

Session-based authentication keeps user info on the server to track login status.

Configure express-session in NestJS to manage sessions.

Store and check user info in req.session to control access.

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

  1. Step 1: Understand session-based authentication

    Session-based authentication stores user info on the server to track login status across requests.
  2. 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.
  3. Final Answer:

    To keep user login information on the server for tracking user sessions -> Option A
  4. 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

  1. Step 1: Identify correct package for session in NestJS

    The official session support in NestJS is provided by '@nestjs/session'.
  2. Step 2: Check import statements

    Only import { SessionModule } from '@nestjs/session'; imports SessionModule from '@nestjs/session', which is correct syntax.
  3. Final Answer:

    import { SessionModule } from '@nestjs/session'; -> Option A
  4. 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?
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';
    }
  }
}
medium
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

  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]
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

  1. Step 1: Review SessionModule options

    In '@nestjs/session', options like 'resave' and 'saveUninitialized' are not valid; they belong to express-session directly.
  2. Step 2: Identify correct option usage

    SessionModule expects options like 'secret' and 'cookie', but not 'resave' or 'saveUninitialized'.
  3. Final Answer:

    'resave' and 'saveUninitialized' are not valid options for SessionModule -> Option C
  4. 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

  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]
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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard