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

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 version of the documentation?
Which UI do you use?
Custom UI
Pre built UI