Skip to main content

Storing data about a user

How the metadata updates work#

In the SuperTokens core, we update the metadata using the following steps:

  1. Load old metadata from DB or use an empty object if we have nothing stored.
  2. Overwrite all root-level properties with the fields of the update object.
  3. Remove all root-level properties with a null value.

This way, you can update parts of the metadata object without loading and merging the whole thing yourself.

important

Only root-level properties are merged into the stored object. Nested objects and all lower-level properties will be replaced.

Example#

  • The stored object has a theme set in preferences, emails enabled in notifications, and a single todo item, telling them to switch to text messages:
{
"preferences": { "theme": "dark" },
"notifications": { "email": true },
"todos": ["use-text-notifs"]
}
  • Now, we want to update this by changing the notification setting and removing the entire todo list:
{
"notifications": { "sms": true },
"todos": null
}
  • The result will be then:
{
"preferences": { "theme": "dark" },
"notifications": { "sms": true }
}
Multi Tenancy

User metadata that is associated with a user is shared across all tenants that that user is a part of. If instead, you want to store usermetadata on a tenent level, you can add a custom key in the JSON like:

{
"tenant1": {
"someKey": "specific to teannt1"
},
"tenant2": {
"someKey": "specific to teannt2"
},
"someKey": "common for all tenants"
}

and then read the appropriate key based on the tenantId.

How to use#

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

let app = express();

app.post("/updateinfo", verifySession(), async (req, res) => {
const session = req.session;
const userId = session.getUserId();

await UserMetadata.updateUserMetadata(userId, { newKey: "data" });

res.json({ message: "successfully updated user metadata" });
});
Which UI do you use?
Custom UI
Pre built UI