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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With