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:

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 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:

let { verifySession } = require("supertokens-node/recipe/session/framework/express");
app.post("/set-role", verifySession(), async (req, 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}    );
    //....});