Skip to main content
Which UI do you use?
Custom UI
Pre built UI

Fetching the JWT and reading claims

Fetching the JWT on the backend#

Method 1) After session verification#

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

let app = express();

app.get("/getJWT", verifySession(), async (req, res) => {

let session = req.session;

let jwt = session.getAccessTokenPayload()["jwt"];

res.json({ token: jwt })
});

Method 2) Without session verification#

import Session from "supertokens-node/recipe/session";

async function getJWT() {
let userId = "...";
// we first get all the sessionHandles (string[]) for a user
let sessionHandles = await Session.getAllSessionHandlesForUser(userId);

sessionHandles.forEach(async (handle) => {
let currSessionInfo = await Session.getSessionInformation(handle)
if (currSessionInfo === undefined) {
return;
}
let currentJWT = currSessionInfo.accessTokenPayload["jwt"];
})
}

Fetching the JWT on the frontend#

import Session from 'supertokens-auth-react/recipe/session';

async function getJWT() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let jwt = (await Session.getAccessTokenPayloadSecurely()).jwt;
}
}

We do not use the useSessionContext React hook here because reading the JWT from that hook doesn't cause an auto-refresh in case the JWT has expired. Instead, calling await Session.getAccessTokenPayloadSecurely() does do an auto refresh making sure that the returned JWT is not expired. Therefore, you want to call the Session.getAccessTokenPayloadSecurely() function as close to the network call as possible.

Reading the JWT claims#

The JWT claims can be read in two ways:

  • Fetch the JWT first (as shown above), verify it and then decode it to get the claims. This can be done using any standard JWT library.; OR
  • Just read the properties of the access token payload (as shown above). This works because when you set claims, those are copied over in the SuperTokens' access token as well as in the issued JWT.