Skip to main content

Storing data in a session


A session is created automatically when the user signs in or signs up.

Types of storage#

A session can hold two types of data:

  • Access token / JWT payload:
    • The access token is a signed cookie that can contain any JSON in it (similar to a JWT).
    • This content is instantly accessible (without a db call) post session verification in an API, and is also accessible on the frontend.
    • The contents can be changed anytime post session verification.
    • An example of what can be stored in this is a user's role.
    • By default, the payload contains:
      {    userId: string,    expiryTime: number,    userData: {        // you can add custom info in here.    }    // ...other fields (which are all implementation details)}
  • Session data:
    • This data is stored in the database, mapped against a session (each session has a constant ID called the sessionHandle).
    • A sessionHandle can be obtained post session verification in an API, after which this data can be fetched / changed.
    • Use this to store any sensitive data associated with a session, that should not be sent to the frontend.
    • The default value is {}

How to store information in a session#

You can store info in the access token or in the session data by overriding the createNewSession function in the Session recipe:

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;
                            // This goes in the access token > userData object                            input.jwtPayload = {                                ...input.jwtPayload,                                someKey: "someValue",                            };
                            // This is stored in the db against the sessionHandle for this session                            input.sessionData = {                                ...input.sessionData,                                someKey: "someValue",                            };
                            return originalImplementation.createNewSession(input);                        },                    };                },            },        })    ]});