Skip to main content

Update Session Data in Database

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!.getSessionDataFromDatabase();

await session!.updateSessionDataInDatabase(
{ 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 updateSessionDataInDatabase 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 getSessionDataFromDatabase for this session.

Method 2) Without session verification#

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

async function updateSessionDataInDatabase() {
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.sessionDataInDatabase;

await Session.updateSessionDataInDatabase(handle,
{ newKey: "newValue", ...currSessionData }
);
})
}
Looking for older versions of the documentation?
Which UI do you use?
Custom UI
Pre built UI