Access the JWT
CAUTION
This guide only applies to scenarios which involve SuperTokens Session Access Tokens.
If you are implementing either, Unified Login or Microservice Authentication, features that make use of OAuth2 Access Tokens, please check the separate page that shows you how to verify those types of tokens.
On the backend
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 })
});
On the frontend
1. Enable exposeAccessTokenToFrontendInCookieBasedAuth
When using cookie based auth, by default, the access token is not readable by the JS on the frontend (since it's stored as httpOnly
cookie). To enable this, you need to set the exposeAccessTokenToFrontendInCookieBasedAuth
config to true
(as shown below
important
If you are only using header-based sessions, you can skip this step
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 on the frontend
What type of UI are you using?
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();
}
}