Skip to main content

Using the verifySession middleware

Requiring an active session#

For your APIs that require a user to be logged in, use the verifySession middleware:

let { verifySession } = require("supertokens-node/recipe/session/framework/express");let { SessionRequest } = require("supertokens-node/framework/express");
app.post("/like-comment", verifySession(), (req: SessionRequest, res) => {    let userId = req.session!.getUserId();     //....});

The session object#

This object exposes the following functions:

  • getHandle: Returns the sessionHandle for this session. This is a constant, unique string per session that never changes for its session.
  • getUserId: Returns the userId of logged in user
  • getSessionData: Returns the session data (stored in the db) that is associated with the session
  • updateSessionData: Set a new JSON object to the session data (stored in the db)
  • getAccessTokenPayload: Returns the access token's payload for this session.
  • updateAccessTokenPayload: Set a new JSON object in the access token (Also available on the frontend)
  • revokeSession: Destroys this session in the db and on the frontend
  • getTimeCreated: Returns the time in milliseconds of when this session was created
  • getExpiry: Returns the time in milliseconds of when this session will expire if not refreshed.
  • getAccessToken: Returns the raw string access token

Optional session verification#

Sometimes, you want an API to be accessible even if there is no session. In that case, you can use the sessionRequired flag:

let { verifySession } = require("supertokens-node/recipe/session/framework/express");let { SessionRequest } = require("supertokens-node/framework/express");
app.post("/like-comment",     verifySession({sessionRequired: false}),     (req: SessionRequest, res) => {        if (req.session !== undefined) {            let userId = req.session.getUserId();        } else {            // user is not logged in...        }    });