Reading roles in the frontend
If a session exists on the frontend, we can read the role by getting information from the session:
- ReactJS
- Plain JavaScript
- React Native
- With React Context
- Without React Context
EmailPasswordAuth
#
Step 1: Wrap the component in which you want to get the info with import React from "react";import { EmailPasswordAuth } from 'supertokens-auth-react/recipe/emailpassword';import Dashboard from "./dashboard";
function ProtectedDashboard(props: any) { return ( <EmailPasswordAuth> <Dashboard /> </EmailPasswordAuth> );}
#
Step 2: This is how to use the session context in a component:import React from "react";import { useSessionContext } from 'supertokens-auth-react/recipe/session';
function Dashboard(props: any) { let { userId, accessTokenPayload } = useSessionContext();
// we use the key "role" here since that's what we // used while setting the payload in the backend. let role = accessTokenPayload.role;
if (role === "admin") { // TODO.. } else { // TODO.. }}
tip
You can pass requireAuth={false}
to EmailPasswordAuth
if you want the <Dashboard />
component to load even if there is no session. In this case, you would need to check if a session exists in the <Dashboard />
component.
import Session from 'supertokens-auth-react/recipe/session';
async function getRole() { if (await Session.doesSessionExist()) {
// we use the key "role" here since that's what we // used while setting the payload in the backend. let role = (await Session.getAccessTokenPayloadSecurely())["role"]; }}
- Via NPM
- Via Script Tag
import SuperTokens from 'supertokens-website';
async function getRole() { if (await SuperTokens.doesSessionExist()) {
// we use the key "role" here since that's what we // used while setting the payload in the backend. let accessTokenPayload = (await SuperTokens.getAccessTokenPayloadSecurely())["role"]; }}
async function getRole() { if (await supertokens.doesSessionExist()) {
// we use the key "role" here since that's what we // used while setting the payload in the backend. let accessTokenPayload = (await supertokens.getAccessTokenPayloadSecurely())["role"]; }}
import SuperTokens from 'supertokens-react-native';
async function getRole() { if (await SuperTokens.doesSessionExist()) {
// we use the key "role" here since that's what we // used while setting the payload in the backend. let accessTokenPayload = (await SuperTokens.getAccessTokenPayloadSecurely())["role"]; }}