Skip to main content

Updating the JWT

caution

Using JWTs is optional and is only required if you want to integrate with another service that relies on JWTs or if you want to integrate with a backend framework that we do not support yet

Method 1) After session verification#

import express from "express";import { verifySession } from "supertokens-node/recipe/session/framework/express";
let app = express();
app.post("/updateinfo", verifySession(), async (req, res) => {
    let session = req.session;
    let currAccessTokenPayload = session.getAccessTokenPayload();
    await session.updateAccessTokenPayload(        { newKey: "newValue", ...currAccessTokenPayload }    );
    res.json({ message: "successfully updated access token payload" })});
  • We first require session verification in order to get the session object
  • Using that object, we call the updateAccessTokenPayload with new content. This content completely overrides the existing object, that's why we first get the currAccessTokenPayload info.
  • The result is that the access token is updated in the user's browser cookies. The change is instantly visible on the frontend and the subsequent backend API calls.

Method 2) Without session verification#

caution

Changes to the access token payload via this method are reflected in the session only once the session is refreshed. So use method (1) whenever possible.

import Session from "supertokens-node/recipe/session";
async function updateJWT() {      let userId = "...";      // we first get all the sessionHandles (string[]) for a user      let sessionHandles = await Session.getAllSessionHandlesForUser(userId);
      // we update all the session's Access Token payloads for this user      sessionHandles.forEach(async (handle) => {            let currAccessTokenPayload = (await Session.getSessionInformation(handle)).accessTokenPayload;
            await Session.updateAccessTokenPayload(handle,                  { newKey: "newValue", ...currAccessTokenPayload }            );      })}