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();

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

// verify user's credentials...

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

await Session.createNewSession(req, 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!" });
})

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";

let app = express();

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

// verify user's credentials...

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

let session = await Session.createNewSessionWithoutRequestResponse(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!" });
})