Get user information on the frontend
With React context
This is supported in supertokens-auth-react >= 0.9.0. For lower versions, see "Without React context" (scroll down).
This is two step process:
- Step 1: This is how to use the session context in a component:
import React from "react";
import { useSessionContext } from 'supertokens-auth-react/recipe/session';
class Dashboard extends React.Component {
render() {
let {userId, jwtPayload} = useSessionContext();
let role = jwtPayload.role;
if (role === "admin") {
// TODO..
} else {
// TODO..
}
}
}
- Step 2: Wrap the above component with
ThirdPartyEmailPasswordAuth
(which provides the context)
import { ThirdPartyEmailPasswordAuth } from 'supertokens-auth-react/recipe/thirdpartyemailpassword';
render() {
return (
<ThirdPartyEmailPasswordAuth>
<Dashboard />
</ThirdPartyEmailPasswordAuth>
);
}
You can read more about ThirdPartyEmailPasswordAuth
in its API guide
Without React context
import Session from 'supertokens-auth-react/recipe/session';
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let jwtPayload = await Session.getJWTPayloadSecurely();
}
import SuperTokens from 'supertokens-website';
if (await SuperTokens.doesSessionExist()) {
let userId = await SuperTokens.getUserId();
let jwtPayload = await SuperTokens.getJWTPayloadSecurely();
}