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";
import supertokens from "supertokens-node";

let app = express();

app.post("/login", async (req, res) => {

// verify user's credentials...

let userId = "userId"; // get from db

await Session.createNewSession(req, res, "public", supertokens.convertToRecipeUserId(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!" });
})
Multi Tenancy

Notice that we pass in the "public" tenantId to the function call above. This is the default tenantId in SuperTokens. The session will be created for that passed in tenantId, and the tId claim in the access token payload will have this value.

CreateNewSession without req / res dependency#

In the above version of the createNewSession function, we pass it the request object and the response object (depending on the language and framework). Whilst this is convenient, you may want to create a new session without using the req and res objects and take control of how the tokens are set in the response. This is possible by using the createNewSessionWithoutRequestResponse function.

import express from "express";
import Session from "supertokens-node/recipe/session";
import supertokens from "supertokens-node";

let app = express();

app.post("/login", async (req, res) => {

// verify user's credentials...

let userId = "userId"; // get from db

let session = await Session.createNewSessionWithoutRequestResponse("public", supertokens.convertToRecipeUserId(userId));

// we can fetch the session tokens from the session object as follows:
const tokens = session.getAllSessionTokensDangerously();
if (tokens.accessAndFrontTokenUpdated) {
// TODO: set access token in response via tokens.accessToken
// TODO: set front-token in response via tokens.frontToken
if (tokens.refreshToken) {
// TODO: set refresh token update in response via tokens.refreshToken
}
if (tokens.antiCsrfToken) {
// TODO: set anti-csrf token update in response via tokens.antiCsrfToken
}
}

res.json({ message: "User logged in!" });
})
Multi Tenancy

Notice that we pass in the "public" tenantId to the function call above. This is the default tenantId in SuperTokens. The session will be created for that passed in tenantId, and the tId claim in the access token payload will have this value.

Looking for older versions of the documentation?
Which UI do you use?
Custom UI
Pre built UI