Skip to main content

Protecting API and website routes

Protecting API routes#

In your API routes you:

  1. Verify that a session exists
  2. Read the userId from the session information
  3. Read and verify that the user has the correct role
import { verifySession } from "supertokens-node/recipe/session/framework/express";import express from "express";import { SessionRequest } from "supertokens-node/framework/express";import UserRoles from "supertokens-node/recipe/userroles";
let app = express();
app.post("/set-role", verifySession(), async (req: SessionRequest, res) => {
    let userId = req.session!.getUserId();
    let roles = (await UserRoles.getRolesForUser(userId)).roles;
    if (roles.includes("admin")) {        // ...    } else {        // ...    }
    //....});

Protecting website routes#

On your frontend:

  1. Verify that a session exists
  2. Use the getAccessTokenPayloadSecurely function to get session information
  3. Read and verify that the user has the correct role
import React from "react";import { useSessionContext } from 'supertokens-auth-react/recipe/session';
function Dashboard(props: any) {      let session = useSessionContext();
      if (session.loading) {        return null;      }
      if (!session.doesSessionExist) {        // TODO      } else {        // we use the key "roles" here since that's what we        // used while setting the payload in the backend.         let roles: string[] = session.accessTokenPayload.roles;
        if (roles.includes("admin")) {                // TODO..        } else {                // TODO..        }      }}