How to add isAuth and access_token to express-session

84 Views Asked by At

I defined the request type as "any" but I realized it shouldn't be "any" and it also can't be "Request". I need to extend express-session to create a custom session type. How can I do that, and add the following information to the request session?

access_token : string
userinfo: {
sub: 'Diur4_PcorTDFMRP99pgP9Qwkclxg4',
name: 'John Kay',
family_name: 'Kay',
given_name: 'John',
picture: 'https://graph.microsoft.com/v1.0/me/photo/$value',
email: '[email protected]'
}
isAuth:boolean

req.session.access_token = access_token;
req.session.userinfo = Userinformtion;
req.session.isAuth = true;  //save session

const isAuth = (req:any, res: Response, next: NextFunction) =\> {
if (req.session.isAuth) {
next();
} else {
res.render("landing");
}
};
1

There are 1 best solutions below

0
Wesley LeMahieu On

In order to add extra session data to an Express session, you would simply define it like you did in your writeup. Here's a working example I use:

export default (req: RequestI, res: Response): void => {
  const { timezone } = req.body;
  if (req.session) {
    if (timezone) {
      req.session.timezone = timezone;
    }
  }
  res.send();
};

This is a simple route handler for an express endpoint. If you POST timezone and the end-user is signed-in, then their session will now contain their timezone. No extra libraries are necessary for that, just express and express-session.