Skip to main content

Securing your API and frontend routes

Protecting APIs#

Requiring an active session#

For your APIs that require a user to be logged in, use the verifySession middleware

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 userId = req.session!.getUserId();
//....
});

The verifySession function returns a 401 to the frontend if a session doesn't exist, or if the access token has expired, in which case, our frontend SDK automatically refreshes the session.

In case of successful session verification, you get access to a session object using which you can get the user's ID, or manipulate the session information.

Microservice authentication#

For authentication between microservices on your backend, checkout the microservice auth guide.

Protecting frontend routes#

You can use the doesSessionExist function to check if a session exists.

import Session from 'supertokens-web-js/recipe/session';

async function doesSessionExist() {
if (await Session.doesSessionExist()) {
// user is logged in
} else {
// user has not logged in yet
}
}

See also#

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