Skip to main content

Update Session Data

Method 1) After session verification#

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("/updateinfo", verifySession(), async (req: SessionRequest, res) => {

let session = req.session;

let currSessionData = session!.getSessionData();

await session!.updateSessionData(
{ newKey: "newValue", ...currSessionData }
);

res.json({ message: "successfully updated Session data in the database" })
});
  • We first require session verification in order to get the session object
  • Using that object, we call the updateSessionData with new content. This content completely overrides the existing object, that's why we first get the currSessionData info.
  • The result is that the session data stored in the database (against the verified session) is updated. The change is instantly visible to other calls of getSessionData for this session.

Method 2) Without session verification#

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

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

// we update all the session's data for this user
sessionHandles.forEach(async (handle) => {
let currSessionInfo = await Session.getSessionInformation(handle)
if (currSessionInfo === undefined) {
return;
}
let currSessionData = currSessionInfo.sessionData;

await Session.updateSessionData(handle,
{ newKey: "newValue", ...currSessionData }
);
})
}
Which frontend SDK do you use?
supertokens-web-js / mobile
supertokens-auth-react