React Reference - PropelAuth Docs

React

The @propelauth/react library is designed for React frontends. This could be vanilla React managed by Vite, Next.js (either Pages or App router) with a separate backend, create-react-app, etc.


Installation

npm install @propelauth/react

Configuration

We need to tell PropelAuth where our application is running so that it will allow requests from our application. Go to the Frontend Integration section of your PropelAuth dashboard, and enter http://localhost:3000 into the Application URL field:

While we're here, we'll also copy the Auth URL into an .env file, which we'll use in a second:

.env

# Test environment only, in production, we'll use our own domain
REACT_APP_AUTH_URL=https://something.propelauthtest.com

# If you are using Vite:
# VITE_AUTH_URL=https://something.propelauthtest.com

Initialization

At the root of your application, wrap your app in an AuthProvider component.

index.js

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

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <AuthProvider
        authUrl={process.env.REACT_APP_AUTH_URL}
        minSecondsBeforeRefresh={120}
    >
        <YourApp />
    </AuthProvider>,
    document.getElementById("root")
);

The AuthProvider is responsible for fetching the current user's authentication information. If your entire application requires the user to be logged in (for example, for a dashboard), use RequiredAuthProvider instead and you'll never have to check isLoggedIn.

Authorization in the React library

On the frontend, authorization is useful for hiding UI elements that the user doesn't have access to. You will still need to implement authorization on the backend to prevent users from accessing data they shouldn't.

For example, you may want to hide the "Billing" page from users who aren't admins. You can do this by using the UserClass to check if the user has the "Admin" role.

const Sidebar = withRequiredAuthInfo(({userClass}) => {
    const router = useRouter()
    const orgId = router.query.orgId as string

const isAdmin = userClass.isAtLeastRole(orgId, "Admin")
    return <div>
        <div>Dashboard</div>
        <div>Reports</div>
        {isAdmin && <div>Billing</div>}
    </div>
})

AuthProvider

AuthProvider is the provider of a React context that manages the current user's access token and metadata. You cannot use the other hooks without it. AuthProvider is the component that manages authentication information and all other components fetches from it.

It is recommended to put the AuthProvider component at the top level of your application, so it never unmounts.

Properties

index.js

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

## [RequiredAuthProvider](https://docs.propelauth.com/reference/frontend-apis/react?ref=propelauth.mymidnight.blog#required-auth-provider)

If your entire application requires a user to be logged in, you should prefer the `RequiredAuthProvider`. Similar to the [AuthProvider](https://docs.propelauth.com/reference/frontend-apis/react?ref=propelauth.mymidnight.blog#auth-provider), the RequiredAuthProvider manages the current user's [access token](https://docs.propelauth.com/recipes/access-tokens) and metadata.

However, the RequiredAuthProvider will also redirect the user to the login page if they are not logged in. You can override this behavior by providing a your own `displayIfLoggedOut` property.

### Properties

### index.js

```javascript
import { RequiredAuthProvider, RedirectToLogin } from "@propelauth/react";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <RequiredAuthProvider
        authUrl={process.env.REACT_APP_AUTH_URL}
        minSecondsBeforeRefresh={120}
        displayWhileLoading={<Loading />}
        displayIfLoggedOut={<RedirectToLogin />}
    >
        <YourApp />
    </RequiredAuthProvider>,
    document.getElementById("root")
);

Client

Creates an authentication client which manages your user's access token, fetches user information, and provides other useful authentication functions.

By default a client will be created and managed automatically by the AuthProvider or RequiredAuthProvider. Optionally, you can create your own client which can be useful when sharing a client between a React and non-React context.

Properties

Example

import { AuthProvider, createClient } from '@propelauth/react'

const customClient = createClient({
    authUrl: process.env.REACT_APP_AUTH_URL
    skipInitialFetch: false,
    enableBackgroundTokenRefresh: true,
    disableRefreshOnFocus: false,
    minSecondsBeforeRefresh: 120
});

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <AuthProvider
        client={customClient}
    >
        <YourApp />
    </AuthProvider>,
    document.getElementById("root")
);

withAuthInfo

withAuthInfo wraps a component and automatically adds auth information to the props of the component.

Arguments

Injected Properties

Signature

import {withAuthInfo} from "@propelauth/react"

withAuthInfo(Component, {
    displayWhileLoading: <div>Loading...</div>
})

Example

const WelcomeMessage = withAuthInfo(props => {
    if (props.isLoggedIn) {
        return <div>Welcome, {props.user.email}!</div>
    } else {
        return <div>You aren't logged in</div>
    }
})

withRequiredAuthInfo

withRequiredAuthInfo wraps a component and automatically adds auth information to the props of the component. It will not render the wrapped component if the user is not logged in, instead, by default, it will redirect the user to the login page.

Arguments

Injected Properties

Signature

import {withRequiredAuthInfo} from "@propelauth/react"

withRequiredAuthInfo(Component, {
    displayWhileLoading: <div>Loading...</div>,
    displayIfLoggedOut: <RedirectToLogin />,
})

Example

const WelcomeMessage = withRequiredAuthInfo(props => {
    return <div>Welcome, {props.user.email}!</div>
})

useAuthInfo

AuthInfo is a React hook that returns the current user's information. It is similar to withAuthInfo, but instead of injecting the information into a component, it returns it from a hook.

Properties

Signature

import {useAuthInfo} from "@propelauth/react"

const authInfo = useAuthInfo()

Example

const WelcomeMessage = () => {
    const authInfo = useAuthInfo()

if (authInfo.loading) {
        return <div>Loading...</div>
    } else if (authInfo.isLoggedIn) {
        return <div>Welcome, {authInfo.user.email}!</div>
    } else {
        return <div>You aren't logged in</div>
    }
}

useLogoutFunction

useLogoutFunction is a React hook that returns a function that will log the user out. It is most commonly used for creating a logout button.

The returned function takes a single argument which is whether or not to redirect the user to your pre-configured logout redirect URL. This defaults to false.

Signature

import {useLogoutFunction} from "@propelauth/react"

const logout = useLogoutFunction()
await logout(false)

Example

const LogoutButton = () => {
    const logout = useLogoutFunction()
    return <button onClick={() => logout(false)}>Logout</button>
}

useRedirectFunctions

useRedirectFunctions is a React hook that returns a collection of functions which redirect the user to useful locations. Each function takes in an optional options argument which can control features like where the user returns to after logging in.

Returned Functions

Signature

import {useRedirectFunctions} from "@propelauth/react"

const {
    redirectToLoginPage,
    redirectToSignupPage,
    redirectToAccountPage,
    redirectToOrgPage,
    redirectToCreateOrgPage,
    redirectToSetupSAMLPage,
} = useRedirectFunctions()

redirectToLoginPage({
    postLoginRedirectUrl: window.location.href,
    userSignupQueryParameters: {
        "ref": "my-cool-blog-post"
    }
})

Example

const NavbarLoginButtons = withAuthInfo((props) => {
    const { redirectToLoginPage, redirectToSignupPage, redirectToAccountPage } = useRedirectFunctions()

if (props.isLoggedIn) {
        return <img src={props.user.pictureUrl} onClick={() => redirectToAccountPage()} />
    } else {
        return <div>
            <button onClick={() => redirectToLoginPage()}>Login</button>
            <button onClick={() => redirectToSignupPage()}>Signup</button>
        </div>
    }
})

useHostedPageUrls

useHostedPageUrls is a React hook that returns a collection of functions which get URLs of useful locations. Each function takes in an optional options argument which can control features like where the user returns to after logging in.

Returned Functions

Signature

import {useHostedPageUrls} from "@propelauth/react"

const {
    getLoginPageUrl,
    getSignupPageUrl,
    getAccountPageUrl,
    getOrgPageUrl,
    getCreateOrgPageUrl,
    getSetupSAMLPageUrl,
} = useHostedPageUrls()

getLoginPageUrl({
    postLoginRedirectUrl: window.location.href,
    userSignupQueryParameters: {
        "ref": "my-cool-blog-post"
    }
})

Example

const NavbarLoginButtons = withAuthInfo((props) => {
    const { getLoginPageUrl, getSignupPageUrl, getAccountPageUrl } = useHostedPageUrls()
    if (props.isLoggedIn) {
        return <img src={props.user.pictureUrl} onClick={() => { window.location.href = getAccountPageUrl() }} />
    } else {
        return <div>
            <a href={getLoginPageUrl()}>Login</a>
            <a href={getSignupPageUrl()}>Signup</a>
        </div>
    }
})

RedirectToLogin

A React component that redirects the user to the login page. It's a helpful wrapper around the useRedirectFunctions hook, specifically for login.

Properties

import {RedirectToLogin} from "@propelauth/react"

<RedirectToLogin
    postLoginRedirectUrl={"https://app.example.com/somewhere-else"}
    userSignupQueryParameters={{
        "ref": "my-cool-blog-post"
    }}
/>

RedirectToSignup

A React component that redirects the user to the signup page. It's a helpful wrapper around the useRedirectFunctions hook, specifically for signup.

Properties

import {RedirectToSignup} from "@propelauth/react"

<RedirectToSignup
    postSignupRedirectUrl={"https://app.example.com/somewhere-else"}
/>

User

This is the object that contains all the information about the current user. It is returned from withAuthInfo, withRequiredAuthInfo, and useAuthInfo.

Properties

UserClass

Similar to User, but instead of just being a JSON object, this is a class with helper functions (e.g. getOrg, isImpersonating). It is returned from withAuthInfo, withRequiredAuthInfo, and useAuthInfo.

Properties

In addition to all the properties on User, this contains:

Example

const WelcomeMessage = withRequiredAuthInfo(({userClass}) => {
    return <div>
        Welcome, {userClass.firstName}!
        {userClass.isImpersonating() && <div>You are being impersonated by {userClass.impersonatorUserId}</div>}
    </div>
})

OrgMemberInfoClass

Similar to OrgMemberInfo, but instead of just being a JSON object, this is a class with helper functions (e.g. isRole, hasPermission). It is returned from functions on the UserClass like UserClass.getOrg and UserClass.getOrgByName.

Properties

const org = userClass.getOrg("my-org-id")
const isAdmin = org?.isRole("Admin")
if (isAdmin) {
    console.log("User is an admin in", org.orgName)
}

OrgHelper

OrgHelper is a helper class for accessing the user's organization information. It is returned from withAuthInfo, withRequiredAuthInfo, and useAuthInfo.

You can also access it directly from useOrgHelper if you don't need the other user information.

Signature

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,
    // returns org information for a given org by name
    getOrgByName: (orgName: string) => OrgMemberInfo | undefined,
}

type OrgMemberInfo = {
    orgId: string,
    orgName: string,
    urlSafeOrgName: string
    // The role of the user within this organization
    userAssignedRole: string
    userPermissions: string[]
}

Example

const OrgList = withRequiredAuthInfo(({orgHelper}) => {
    return <ul>
        {orgHelper.getOrgs().map(org => {
            return <li key={org.orgId}>{org.orgName}</li>
        })}
    </ul>
})

AccessHelper

A helper class for accessing the user's roles and permissions. It is returned from withAuthInfo, withRequiredAuthInfo, and useAuthInfo.

Properties

Example

const Sidebar = withRequiredAuthInfo(({accessHelper}) => {
    const router = useRouter()
    const orgId = router.query.orgId as string

const isAdmin = accessHelper.isAtLeastRole(orgId, "Admin")
    return <div>
        <div>Dashboard</div>
        <div>Reports</div>
        {isAdmin && <div>Billing</div>}
    </div>
})

Tokens

A helper class for generating access tokens.

Properties

Example

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

const orgId = // get orgId from somewhere

async function getOrgAccessToken(orgId) {
    const authInfo = useAuthInfo();
    const orgAccessToken = await authInfo.tokens.getAccessTokenForOrg(orgId);
    return orgAccessToken
}