Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use session object in guards with nest-session

Tags:

nestjs

In NestJS, using nest-session, I would like to use session object within a guard (CanActivate).

Inside a controller's action this is done by using @Session() but I can't find nor figure out how to fetch this data withing a guard.

like image 588
Nathanael Demacon Avatar asked Feb 03 '26 01:02

Nathanael Demacon


1 Answers

First of all create an Interface that contains the session object and extends the express Request object because the session object is a field that nestjs creates and doesn't exists on the Request object.

import { Request } from 'express';
export interface IRequest extends Request {
   session: any;
}

Then on your guard, you must import the interface, create a variable with this type then use the execution context to get the request and that's it, the req variable contain the Request object, you can use req.session to get the session object.

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { IRequest } from './app.interface'; //Import interface

@Injectable()
export class Guard implements CanActivate {
  constructor() {}
  canActivate(context: ExecutionContext): boolean {
    const req: IRequest = context.switchToHttp().getRequest(); //Request Object
    const session = req.session; //Session Object
    /*
        Do whatever you want with your session here ...
    */
    return true;
  }
}

You can find more information about the Request object here: https://docs.nestjs.com/controllers#request-object https://expressjs.com/en/api.html#req

like image 173
Juan Rambal Avatar answered Feb 04 '26 16:02

Juan Rambal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!