Skip to main content

Securing your API and frontend routes

Protecting APIs#

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.

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 website routes#

caution

These instructions only apply to scenarios in which you are using SuperTokens Access Tokens.

If you are implementing Unified Login with OAuth2 Access Tokens, please check the specific use case page for relevant information.

You can wrap your components with the <SessionAuth> react component. This will ensure that your component renders only if the user is logged in. If they are not logged in, the user will be redirected to the login page.

import React from "react";
import {
BrowserRouter,
Routes,
Route,
} from "react-router-dom";
import { SessionAuth } from "supertokens-auth-react/recipe/session";
import MyDashboardComponent from "./dashboard";

class App extends React.Component {
render() {
return (
<BrowserRouter>
<Routes>
<Route path="/dashboard" element={
<SessionAuth>
{/*Components that require to be protected by authentication*/}
<MyDashboardComponent />
</SessionAuth>
} />
</Routes>
</BrowserRouter>
);
}
}

See also#

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