Access Session Data - SuperTokens Docs

Access Session Data

Learn how to access session data including JWT tokens, tenant IDs, and user sessions across different programming languages and frameworks.

Overview

The session data is accessible, both in the backend and on the frontend, after a user has successfully logged in. This guide shows you how to access different session properties.

Before you start


Access the JWT Token

On the backend

Node.js

import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";

let app = express();

app.get("/getJWT", verifySession(), async (req, res) => {
  let session = req.session;

let jwt = session.getAccessToken();

res.json({ token: jwt });
});

Hapi

import Hapi from "@hapi/hapi";
import { verifySession } from "supertokens-node/recipe/session/framework/hapi";
import { SessionRequest } from "supertokens-node/framework/hapi";

let server = Hapi.server({ port: 8000 });

server.route({
  path: "/getJWT",
  method: "get",
  options: {
    pre: [{
      method: verifySession(),
    },],
  },
  handler: async (req: SessionRequest, res) => {
    let session = req.session;

let jwt = session!.getAccessToken();
    return res.response({ token: jwt }).code(200);
  },
});

Fastify

import Fastify from "fastify";
import { verifySession } from "supertokens-node/recipe/session/framework/fastify";

let fastify = Fastify();

fastify.get(
  "/getJWT",
  {
    preHandler: verifySession(),
  },
  (req, res) => {
    let session = req.session;

let jwt = session.getAccessToken();
    res.send({ token: jwt });
  },
);

Aws Lambda

import { verifySession } from "supertokens-node/recipe/session/framework/awsLambda";
import { SessionEvent } from "supertokens-node/framework/awsLambda";

async function getJWT(awsEvent: SessionEvent) {
  let session = awsEvent.session;

let jwt = session!.getAccessToken();

return {
    body: JSON.stringify({ token: jwt }),
    statusCode: 200,
  };
}

exports.handler = verifySession(getJWT);

Koa

import KoaRouter from "koa-router";
import { verifySession } from "supertokens-node/recipe/session/framework/koa";
import { SessionContext } from "supertokens-node/framework/koa";

let router = new KoaRouter();

router.get("/getJWT", verifySession(), (ctx: SessionContext, next) => {
  let session = ctx.session;

let jwt = session!.getAccessToken();
  ctx.body = { token: jwt };
});

On the frontend

1. Enable exposeAccessTokenToFrontendInCookieBasedAuth

When using cookie based auth, by default, the access token is not readable by the SDK on the frontend (since it’s stored as httpOnly cookie). To enable this, you need to set the exposeAccessTokenToFrontendInCookieBasedAuth parameter to true.

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

SuperTokens.init({
  supertokens: {
    connectionURI: "..."
  },
  appInfo: {
    apiDomain: "...",
    appName: "...",
    websiteDomain: "..."
  },
  recipeList: [Session.init({
    exposeAccessTokenToFrontendInCookieBasedAuth: true,
  }),],
});

2. Read the access token

import Session from "supertokens-auth-react/recipe/session";

async function getJWT() {
  if (await Session.doesSessionExist()) {
    let userId = await Session.getUserId();
    let jwt = await Session.getAccessToken();
  }
}

Access the Tenant ID

The session’s access token payload contains the tenant ID in the tId claim. You can access it in the following ways:

On the backend

Node.js

import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express";

let app = express();

app.post("/like-comment", verifySession(), (req: SessionRequest, res) => {
  let tenantId = req.session!.getTenantId();
  //....
});

Fetch all user sessions

Given a user ID, you can fetch all sessions that are active for that user in the following way:

Node.js

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

async function getSessions() {
  let userId = "someUserId"; // fetch somehow

let sessionHandles = await Session.getAllSessionHandlesForUser(userId);

sessionHandles.forEach((handle) => {
    /* we can do the following with the handle:
     * - revoke this session
     * - change access token payload or session data
     * - fetch access token payload or session data
     */
  });
}