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 setJwtPayload in the init function:

let SuperTokens = require("supertokens-node");let Session = require("supertokens-node/recipe/session);
SuperTokens.init({    SuperTokens: {...},    appInfo: {...},    recipeList: [        Session.init({            override: {                functions: (originalImplementation) => {                    return {                        ...originalImplementation,                        createNewSession: async (input) => {                            let userId = input.userId;
                            let role = "admin"; // TODO: fetch role based on userId
                            input.jwtPayload = {                                ...input.jwtPayload,                                role                            };
                            return originalImplementation.createNewSession(input);                        },                    };                },            },        })    ]});

2) In any API call post login#

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

let Session = require("supertokens-node/recipe/session");
app.post("/set-role",  Session.verifySession(), async (req, res) => {    let userId = req.session.getUserId();
    let role = "admin"; // TODO: fetch based on user
    // Note that this will override any existing payload    // that you may have provided earlier.    await req.session.updateJWTPayload({        role    });
    //....});