Skip to content

React Library Reference

Installation

$ npm install --save @propelauth/react 
$ yarn add @propelauth/react

Set up - AuthProvider

AuthProvider is the provider of a React context that manages the current user's access token and metadata. You cannot use any of the other hooks without it.

In other words, the AuthProvider is the component that actually manages authentication information, and every other component/function fetches from it.

It's best to put it at the top level of your application, so it never unmounts.

import {AuthProvider} from "@propelauth/react";

ReactDOM.render(
    <AuthProvider authUrl={process.env.REACT_APP_AUTH_URL}> // (1)
        <YourApp/>
    </AuthProvider>,
    document.getElementById("root")
);
  1. The authUrl is the base URL where your authentication pages are hosted. You can find this under the Frontend Integration section for your project.

Get current user information

There are three options for getting the current user's information:

import {withAuthInfo} from '@propelauth/react';

function MinimalExample(props) {
    // isLoggedIn and user are injected automatically from withAuthInfo below
    if (props.isLoggedIn) {
        return <div>You are logged in as {props.user.email}</div>
    } else {
        return <div>You are not logged in</div>
    }
}

export default withAuthInfo(MinimalExample); // (1)
  1. A React Higher-Order Component that provides common values like isLoggedIn and accessToken. These values are injected into the props of your component.
import {withRequiredAuthInfo} from '@propelauth/react';

function MinimalExample(props) {
    // user is injected automatically from withRequiredAuthInfo below
    return <div>You are logged in as {props.user.email}</div>
}

export default withRequiredAuthInfo(MinimalExample); // (1)
  1. Similar to withAuthInfo, except if the user isn't logged in, they are redirected to the login page (that behavior is configurable).
import {useAuthInfo} from '@propelauth/react';

function MinimalExample() {
    const authInfo = useAuthInfo()

    // Unlike the higher order functions, we need to check the loading case now
    if (authInfo.loading) {
        return <div>Loading...</div>
    } else if (authInfo.isLoggedIn) {
        return <div>You are logged in as {props.user.email}</div>
    } else {
        return <div>You are not logged in</div>
    }
}

export default MinimalExample; 

When is an external API call made?

The AuthProvider manages all external API requests. withAuthInfo, withRequiredAuthInfo, and useAuthInfo are only getting information out of it and make no requests themselves. In other words, you can (and should) add as many uses of these functions as you need - they will not cause you to make additional requests.

withAuthInfo

withAuthInfo(Component, {
    displayWhileLoading: <div>Loading...</div>, // (1)
})
  1. A React element to display while the AuthProvider is fetching auth information. Defaults to an empty element

which will inject the following props into Component:

Prop Description
accessToken If the user is logged in, this is a string you can use to access your APIs on behalf of this user. Otherwise, null
isLoggedIn Whether or not the user is logged in
orgHelper An object with useful functions for managing organizations
user If the user is logged in, this contains metadata about them. Otherwise, null

withRequiredAuthInfo

withRequiredAuthInfo(Component, {
    displayWhileLoading: <div>Loading...</div>, // (1)
    displayIfLoggedOut: <div>You are logged out</div> // (2)
})
  1. A React element to display while the AuthProvider is fetching auth information. Defaults to an empty element
  2. A React element to display if the current user is logged out. Defaults to <RedirectToLogin />

This is identical to withAuthInfo, except Component is only rendered if the user is logged in. You are guaranteed that isLoggedIn is true and the accessToken is not null.

useAuthInfo

function Component() {
    const authInfo = useAuthInfo()
    // ...rest of the component
}

A React hook which gets auth information. authInfo contains:

Key Description
loading True if the AuthProvider is still fetching auth information. This will only happen once when the application is first loaded.
accessToken If the user is logged in, this is a string you can use to access your APIs on behalf of this user. Otherwise, null
isLoggedIn Whether or not the user is logged in
orgHelper An object with useful functions for managing organizations
user If the user is logged in, this contains metadata about them. Otherwise, null

Logout

function LogoutButton() {
    const logoutFn = useLogoutFunction(); // (1)
    return <button onClick={() => logoutFn(true) /*(2)*/}>Logout</button>
}
  1. A React hook that returns a function which logs the current user out.
  2. The function takes a single parameter redirectOnLogout. If true, the function will redirect the user to the logout URL configured in the Frontend Integration section of your project.

useRedirectFunctions

function SignupAndLoginButtons() {
    const {redirectToSignupPage, redirectToLoginPage} = useRedirectFunctions();
    return <div>
        <button onClick={redirectToSignupPage}>Signup</button>
        <button onClick={redirectToLoginPage}>Login</button>
    </div>
}

A React hook that returns a collection of functions which redirect the user to useful locations.

Function Description
redirectToAccountPage() Redirects the user to the account hosted authentication page, where they can view/modify their user information.
redirectToSignupPage() Redirects the user to the signup hosted authentication page.
redirectToLoginPage() Redirects the user to the login hosted authentication page.
redirectToOrgPage(orgId?) Redirects the user to an organization management hosted authentication page. If orgId is specified, redirect to that organization's page. If none is specified, a default is chosen deterministically.
redirectToCreateOrgPage() Redirects the user to the hosted authentication page where they can create organizations.

RedirectToLogin

function Private(props) {
    return <div>You are logged in as {props.user.email}</div>
}

export default withRequiredAuthInfo(Private, {
    displayIfLoggedOut: <RedirectToLogin />, //(1)
});
  1. When this component is rendered, if the user isn't logged in, it will redirect to the login page

A React component that redirects the user to the login hosted authentication page when rendered. This is identical to calling redirectToLoginPage from useRedirectFunctions.

RedirectToSignup

function Private(props) {
    return <div>You are logged in as {props.user.email}</div>
}

export default withRequiredAuthInfo(Private, {
    displayIfLoggedOut: <RedirectToSignup />, //(1)
});
  1. When this component is rendered, if the user isn't logged in, it will redirect to the signup page

A React component that redirects the user to the signup hosted authentication page when rendered. This is identical to calling redirectToSignupPage from useRedirectFunctions.

Schemas

The User object

type User = {
    userId: string;

    email: string;
    emailConfirmed: boolean;

    username?: string;
    firstName?: string;
    lastName?: string;
    pictureUrl?: string;

    locked: boolean;
    enabled: boolean;
    mfaEnabled: boolean;
}

The orgHelper

The orgHelper exists to make the current user's organization information easy to manage. It's an object which has the following functions (types included) on it:

type OrgHelper = {
    // returns all orgs that the user is a member of
    getOrgs: () => OrgMemberInfo[],
    // returns all org ids that the user is a member of
    getOrgIds: () => string[],
    // returns org information for a given orgId
    getOrg: (orgId: string) => OrgMemberInfo | undefined,

    // Applications have users that can be in multiple organizations.
    // However, very commonly, your user will only interact with one at a time.
    // These functions allow you to select an org, which your application can fetch.
    // See the examples below for more details
    selectOrg: (orgId: string) => void,

    // inferDefault, if true, will deterministically select an organization 
    //   if one hasn't yet been explicitly selected.
    // The order is:
    //   - Organizations selected with selectOrg
    //   - Previously selected organizations (uses localStorage to survive new tabs/refreshes)
    //   - Alphabetical order by name
    // Default is true
    getSelectedOrg: (inferDefault?: boolean) => OrgMemberInfo | undefined,
    getNotSelectedOrgs: (inferDefault?: boolean) => OrgMemberInfo[],
}
type OrgMemberInfo = {
    orgId: string;
    orgName: string;
    userRole: UserRole;
};

enum UserRole {
  Member = 0,
  Admin = 1,
  Owner = 2,
};

UserRole

B2B projects come with a standard permissions pattern where each user can be one of a Member, Admin, or Owner. Only Admins or Owners are able to invite new users, and we make sure there is always at least one Owner in every Org.

If you are looking for a more complex permissions model, please reach out at beta@propelauth.com.

Examples

Display the users email for logged in users

function Example(props) {
    // isLoggedIn and user are injected automatically from withAuthInfo below
    if (props.isLoggedIn) {
        return <div>Email: {props.user.email}</div>
    } else {
        return <div>Email: None</div>
    }
}

export default withAuthInfo(Example);

Display buttons for signup and login

function SignupAndLoginButtons() {
    const {redirectToSignupPage, redirectToLoginPage} = useRedirectFunctions();
    return <div>
        <button onClick={redirectToSignupPage}>Signup</button>
        <button onClick={redirectToLoginPage}>Login</button>
    </div>
}

Display Signup and Login buttons (for logged out users) or a Logout button (for logged in users)

import {withAuthInfo, useLogoutFunction, useRedirectFunctions} from '@propelauth/react';

function AuthenticationButtons({isLoggedIn}) {
    const logoutFn = useLogoutFunction()
    const {redirectToSignupPage, redirectToLoginPage} = useRedirectFunctions()

    if (isLoggedIn) {
        return <button onClick={() => logoutFn(true)}>Logout</button>
    } else {
        return <div>
            <button onClick={redirectToSignupPage}>Signup</button>
            <button onClick={redirectToLoginPage}>Login</button>
        </div>
    }
}

export default withAuthInfo(AuthenticationButtons);

Display the user's profile picture

You must enable Profile Picture support first.

import {withAuthInfo} from '@propelauth/react';

function ProfilePicture({isLoggedIn, user}) {
    if (isLoggedIn) {
        return <img src={user.pictureUrl} />
    } else {
        return null;
    }
}

export default withAuthInfo(ProfilePicture)

Allow users to select an organization, and display it in a different component

// OrgSelector.jsx
// Allow users to select an organization
function OrgSelector(props) {
    if (!props.isLoggedIn) return <span/>

    const orgs = props.orgHelper.getOrgs();

    // getSelectedOrg() will infer an intelligent default 
    //   in case they haven't selected one yet
    const selectedOrg = props.orgHelper.getSelectedOrg();
    const handleChange = (event) => props.orgHelper.selectOrg(event.target.value);

    return <select value={selectedOrg.orgId} onChange={handleChange}>
        {orgs.map(org => <option value={org.orgId}>{org.orgName}</option>)}
    </select>
}

export default withAuthInfo(OrgSelector);


// SelectedOrg.jsx
// Display the selected organization
function SelectedOrg(props) {
    if (!props.isLoggedIn) return <span/>

    const selectedOrg = props.orgHelper.getSelectedOrg();
    if (selectedOrg) {
        return <div>You have currently selected {selectedOrg.orgName}</div>
    } else {
        // getSelectedOrg would have picked a default if any orgs exited
        return <div>You do not belong to any orgs</div>
    }
}

export default withAuthInfo(SelectedOrg);