Skip to main content

Creating a new session

How to create a new session#

Create a new session after verifying user's credentials in the login API, or after creating a new user in the sign up API.

import express from "express";import Session from "supertokens-node/recipe/session";
let app = express();"/login", async (req, res) => {
    // verify user's credentials...
    let userId = "userId"; // get from db
    await Session.createNewSession(res, userId);
    /* a new session has been created.     * - an access & refresh token has been attached to the response's cookie     * - a new row has been inserted into the database for this new session    */
    res.json({ message: "User logged in!" });})

Storing session information#

The full signature of createNewSession is:

import { SessionContainer } from "supertokens-node/recipe/session";
type createNewSession = (    res: any,    userId: string,    accessTokenPayload?: any,    sessionData?: any,) => Promise<SessionContainer>;

A session can hold two types of data:

  • Access token:
    • 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:
      type AccessTokenInfo = {    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 {}
What type of UI do you want to use?
Custom UI
Pre built UI