Skip to main content

Checking if a session exists on the frontend

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 {doesSessionExist} = useSessionContext();
            if (!doesSessionExist) {                  // display UI to take the user to login            } else {                  // Your component for logged in user.            }      }}

Step 2: Wrap the above component with EmailPasswordAuth (which provides the context)#

import { EmailPasswordAuth } from 'supertokens-auth-react/recipe/emailpassword';
render() {
      /*       * 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 (            <EmailPasswordAuth requireAuth={false}>                  <Dashboard />            </EmailPasswordAuth>      );}