Get user information on the frontend
- ReactJS
- Plain JavaScript
- React Native
- With React Context
- Without React Context
SessionAuth
#
Step 1: Wrap the component in which you want to get the info with import React from "react";import { SessionAuth } from 'supertokens-auth-react/recipe/session';import Dashboard from "./dashboard";
function ProtectedDashboard(props: any) { return ( <SessionAuth requireAuth={true} redirectToLogin={() => {/* ... */ }}> <Dashboard /> </SessionAuth> );}
#
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';
// Your dashboard componentfunction Dashboard(props: any) { let { userId, accessTokenPayload } = useSessionContext();
let role = accessTokenPayload.role;
if (role === "admin") { // TODO.. } else { // TODO.. }}
import Session from 'supertokens-auth-react/recipe/session';
async function getUserInfo() { if (await Session.doesSessionExist()) { let userId = await Session.getUserId(); let accessTokenPayload = await Session.getAccessTokenPayloadSecurely(); }}
- Via NPM
- Via Script Tag
import SuperTokens from 'supertokens-website';
async function getUserInfo() { if (await SuperTokens.doesSessionExist()) { let userId = await SuperTokens.getUserId(); let accessTokenPayload = await SuperTokens.getAccessTokenPayloadSecurely(); }}
async function getUserInfo() { if (await supertokens.doesSessionExist()) { let userId = await supertokens.getUserId(); let accessTokenPayload = await supertokens.getAccessTokenPayloadSecurely(); }}
import SuperTokens from 'supertokens-react-native';
async function getUserInfo() { if (await SuperTokens.doesSessionExist()) { let userId = await SuperTokens.getUserId(); let accessTokenPayload = await SuperTokens.getAccessTokenPayloadSecurely(); }}