Skip to main content

Assigning roles to a session

This can be done at two points in time:

  • 1) During user login / sign up
  • 2) In any API call post login

1) During user login / sign up#

We can set an access token payload by passing it to the createNewSession function:

import express from "express";import Session from "supertokens-node/recipe/session";
let app = express();
app.post("/login", async (req, res) => {
    // verify user's credentials...
    let userId = "userId"; // get from db
    let role = "admin"; // TODO: fetch based on user
    await Session.createNewSession(res, userId, { role });
    res.json({ message: "User logged in!" });})

2) In any API call post login#

Post session verification, you can use the updateAccessTokenPayload function to store the user's role:

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("/set-role", verifySession(), async (req: SessionRequest, res) => {
    let userId = req.session!.getUserId();
    let role = "admin"; // TODO: fetch based on user
    // Note that this will override any existing access token payload    // that you may have provided earlier.    await req.session!.updateAccessTokenPayload(        { role }    );
    //....});