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 the user's role in the access token by overriding the createNewSession function in the init function:

import SuperTokens from "supertokens-node";import Session from "supertokens-node/recipe/session";
SuperTokens.init({    supertokens: {        connectionURI: "...",    },    appInfo: {        apiDomain: "...",        appName: "...",        websiteDomain: "..."    },    recipeList: [        Session.init({            override: {                functions: (originalImplementation) => {                    return {                        ...originalImplementation,                        createNewSession: async function (input) {                            let userId = input.userId;
                            let role = "admin"; // TODO: fetch role based on userId
                            input.accessTokenPayload = {                                ...input.accessTokenPayload,                                role                            };
                            return originalImplementation.createNewSession(input);                        },                    };                },            },        })    ]});

2) In any API call post login#

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

import { verifySession } from "supertokens-node/recipe/session/framework/express";import express from "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 }    );
    //....});