Checking if a session exists on the frontend
- ReactJS
- Plain JavaScript
- React Native
- With React Context
- Without React Context
ThirdPartyEmailPasswordAuth
#
Step 1: Wrap the component in which you want to get the info with import React from "react";import { ThirdPartyEmailPasswordAuth } from 'supertokens-auth-react/recipe/thirdpartyemailpassword';import Dashboard from "./dashboard";
function ProtectedDashboard(props: any) {
/* * requireAuth = false means that even if a session doesn't exist, * the dashboard component will be shown. The reason we have this set * here is that if we didn't then doesSessionExist would always be * true in the Dashboard component, in which case you would not * have to check for if a session exists. */ return ( <ThirdPartyEmailPasswordAuth requireAuth={false}> <Dashboard /> </ThirdPartyEmailPasswordAuth> );}
#
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 {doesSessionExist} = useSessionContext();
if (doesSessionExist) { // TODO.. } else { // TODO.. }}
import React from "react";import Session from 'supertokens-auth-react/recipe/session';
class Dashboard extends React.Component { state: { sessionExists: boolean, }
constructor(props: any) { super(props); this.state = { sessionExists: false, } } render() { if (!this.state.sessionExists) { // The user is not logged in } else { // Your component for logged in user. }
return <></> }
componentDidMount = async () => { this.setState({ sessionExists: await Session.doesSessionExist() }); }}
- Via NPM
- Via Script Tag
import SuperTokens from 'supertokens-website';
async function doesSessionExist() { if (await SuperTokens.doesSessionExist()) { // user is logged in } else { // user has not logged in yet }}
async function doesSessionExist() { if (await supertokens.doesSessionExist()) { // user is logged in } else { // user has not logged in yet }}
import SuperTokens from 'supertokens-react-native';
async function doesSessionExist() { if (await SuperTokens.doesSessionExist()) { // user is logged in } else { // user has not logged in yet }}