Skip to main content
Which frontend SDK do you use?
supertokens-web-js / mobile
supertokens-auth-react

Session verification during server side rendering

important

Getting access to the session during server side rendering is only possible using cookie-based sessions. This is the default setting, but you have to keep this in mind if you want to switch to header-based sessions.

1) Call the backend init function on your web server#

If your web server is a different process than the API server, then you should call the SuperTokens backend SDK init function with the Session recipe initialised.

If the web server domain is on a different sub domain than the api domain, then be sure to enable cookie sharing across backend sub domains

2) Use the getSession function#

For server side rendering, we can utilise the getSession function for session verification. The browser will send session cookies along with the request which will be verified by this function resulting in one of these states:

  • Successful verification: This will yield a session object using which you can get the userId of the user.
  • Try refresh token error: This means that the access token has expired and that you should trigger the refresh flow (more on this below).
  • Unauthorised error: This means that the session does not exist, was revoked, or was compromised. Unintuitively, this should also trigger the refresh flow (more on this below) - which will fail and eventually redirect the user to the login screen.

Below is code for how you can use getSession to achieve SSR and get the user's ID from the session:

import express from "express";
import Session from "supertokens-node/recipe/session";
import { Error as SuperTokensError } from "supertokens-node";

let app = express();

app.get("/dashboard", async (req, res, next) => {
try {
let session = await Session.getSession(req, res, {
overrideGlobalClaimValidators: () => {
// this makes it so that no custom session claims are checked
return []
}
});

let userId = session.getUserId();
//...
} catch (err) {
if (SuperTokensError.isErrorFromSuperTokens(err)) {
if (err.type === Session.Error.TRY_REFRESH_TOKEN || err.type === Session.Error.UNAUTHORISED) {
res.redirect("/refresh-session?redirectBack=/dashboard");
} else {
next(err);
}
} else {
next(err)
}
}
});