Skip to main content

Using the verifySession middleware

Verifying a session using the verifySession middleware#

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

import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express";

let app = 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
  • getSessionDataFromDatabase: Returns the session data (stored in the database) that is associated with the session.
  • updateSessionDataInDatabase: Set a new JSON object to the session data (stored in the database)
  • getAccessTokenPayload: Returns the access token's payload for this session. This includes claims defined by you (e.g.: in createNewSession), standard claims (sub, iat, exp) and supertokens specific ones (sessionHandle, parentRefreshTokenHash1, etc.)
  • mergeIntoAccessTokenPayload: Adds key / values into a JSON object in the access token. Set a key to null to remove it from the payload.
  • 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
  • getAllSessionTokensDangerously: Returns an object that contains the raw string representation of all tokens associated with the session along with a boolean that indicates if thee session needs to be updated on the frontend.

getSessionDataFromDatabase vs getAccessTokenPayload#

  • getSessionDataFromDatabase queries the SuperTokens Core to get the information, mapped to that session's handle, from the database. Whereas getAccessTokenPayload reads directly from the access token used in the request.
  • getSessionDataFromDatabase is much slower since it requires a network call.
  • The information stored using updateSessionDataInDatabase (changes the result of getSessionDataFromDatabase function call), is not exposed to the frontend in any way. So if you want to store something sensitive against the session handle, use this method.
  • If you want access to some information in most / all API, like the user's role, then use getAccessTokenPayload and mergeIntoAccessTokenPayload since fetching this information from the session will be very fast (no network call required).

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:

import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express";

let app = 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...
}
}
);

Verifying the claims of a session#

Sometimes, you may also want to check if there are certain claims in the session as part of the verification process. For example, you may want to check that the session has the admin role claim for certain APIs, or that the user has completed 2FA.

This can be done using our session claims validator feature. Let's take an example of using the user roles claim to check if the session has the admin claim:

import { verifySession } from "supertokens-node/recipe/session/framework/express";
import express from "express";
import { SessionRequest } from "supertokens-node/framework/express";
import UserRoles from "supertokens-node/recipe/userroles";

let app = express();

app.post(
"/update-blog",
verifySession({
overrideGlobalClaimValidators: async (globalValidators) => [
...globalValidators,
UserRoles.UserRoleClaim.validators.includes("admin"),
// UserRoles.PermissionClaim.validators.includes("edit")
],
}),
async (req: SessionRequest, res) => {
// All validator checks have passed and the user is an admin.
}
);
  • We add the UserRoleClaim validator to the verifySession function which makes sure that the user has an admin role.
  • The globalValidators represents other validators that apply to all API routes by default. This may include a validator that enforces that the user's email is verified (if enabled by you).
  • We can also add a PermissionClaim validator to enforce a permission.
feature

You can also build your own custom claim validators based on your app's requirements.