Overview
This article provides guidance on how to automatically check a user’s login status and redirect them if they are not authenticated. The Auth0 React Software Development Kit (SDK) is designed to handle this flow by using the withAuthenticationRequired Higher-Order Component (HOC).
Applies To
Solution
The Auth0 React SDK automatically checks for an active user session when the application loads. This process is managed by the Auth0Provider that wraps the application components.
To protect entire pages or routes from unauthenticated access, the recommended approach is to use the withAuthenticationRequired HOC. This component automatically handles the redirection to the login page for any user who is not authenticated.
The following code provides an example implementation:
...
import { Auth0Provider, withAuthenticationRequired } from "@auth0/auth0-react";
...
const ProtectedApp = withAuthenticationRequired(App, {
// You can optionally provide a custom loading component
onRedirecting: () => <div>Loading...</div>,
});
...
root.render(
<Auth0Provider
{...providerConfig}
>
{/* Use the protected component you defined earlier */}
<ProtectedApp />
</Auth0Provider>,
);
...
NOTE: This code snippet is intended for testing and demonstration purposes only. It is not meant for production use and should be thoroughly tested before being deployed.
For more detailed information regarding the withAuthenticationRequired higher-order component, refer to our official documentation on GitHub.