https://supertokens.com/ logo
i

ITEnthusiasm

05/02/2022, 4:41 PM
Does optional
verifySession
still work correctly? 🤔 Even when I set
sessionRequired: false
, I'm getting 401s.
r

rp

05/02/2022, 4:43 PM
Hey! So that’s possible if a session exists, but the access token has expired. In that case, you should refresh the session. This is a different than the session not existing at all, in which case, it will not send a 401 but will let your api logic run
i

ITEnthusiasm

05/02/2022, 4:44 PM
I see. That is indeed difficult. I guess I'll have to work around that then.
(Originally I was hoping to provide session information to all routes and react to invalid sessions. Wasn't aware of this edge case.)
r

rp

05/02/2022, 4:45 PM
The correct thing would be to refresh the session in this case. Since the user is logged in
i

ITEnthusiasm

05/02/2022, 4:59 PM
Yes. But in development I'm in a catch 22 situation since I was seeking to apply
verifySession
globally. I need to call the backend to get a webpage that will enable me to do a refresh. But I can't access that webpage because the user needs to refresh first.
r

rp

05/02/2022, 5:01 PM
So in that case, you can make your own middleware which replaces verifiySession. In that, you can call getSession function which returns a session if successful, else it throws an error. If it throws an unauthorised error, the user is not logged in. If it throws a try refresh token error, you can handle that by returning a 401 with any content (like an html page if you like)
i

ITEnthusiasm

05/02/2022, 5:05 PM
So this?
Copy code
ts
async function mySessionMiddleware(req, res) {
  const session = await Session.getSession(req, res);
  if (!session) throw Error("My Error");
  // ...
}
And another middleware would try to catch that error?
r

rp

05/02/2022, 5:15 PM
Yea.. so if
!session
is true, it means the user is not logged in, so you can call
next
in that. You can do something like:
Copy code
async function mySessionMiddleware(req, res, next) {
 try {
        let session = await Session.getSession(context.req, context.res)
        req.session = session;
        return next();
    } catch (err) {
        if (err.type === Session.Error.TRY_REFRESH_TOKEN) {
          // send a 401 here, with some html content. On the frontend, this should call the refresh API
        } else if (err.type === Session.Error.UNAUTHORISED) {
          // the user is not logged in
          return next();
        } else {
            throw err
        }
    }
}
Note that this should be AFTER the
app.use(middleware())
where
middleware
is imported from supertokens.
i

ITEnthusiasm

05/02/2022, 5:20 PM
Gotcha. Okay. I'll try this out. 🤔 Thanks!
5 Views