Integrating Auth0 user invitations with React applications can be tricky, especially when using the withAuthenticationRequired Higher-Order Component (HOC) from auth0-react. This article bridges that gap by explaining how to process invitation callbacks seamlessly.
Who Should Read This?
You're using React with Auth0 and auth0-react for authentication, and specifically leverage the withAuthenticationRequired HOC. You also use Auth0's Organizations feature with user invitations, and have encountered issues handling user invitation links.
The Challenge
While Auth0 has good documentation for most features, Organizations and invitations in particular lack in-depth coverage for the withAuthenticationRequired use case. The auth0-react documentation outlines what to do if you use loginWithRedirect, but there's no readily available solution for withAuthenticationRequired.
The Solution
Invitation accept URLs typically look like this:
https://your.domain/default/route?invitation=<invitation_code>>&organization=<org_id>>&organization_name=<org_name>
Our goal is to capture the invitation and organization query parameters and pass them to withAuthenticationRequired. Here's how to achieve this:
import { ComponentType } from "react";
import { withAuthenticationRequired } from "@auth0/auth0-react";
import { useSearchParams } from "react-router-dom";
export const withUserAuthenticationRequired = ({ component }: { component: ComponentType }) => {
const [searchParams] = useSearchParams();
const Component = withAuthenticationRequired(component, {
onRedirecting: () => <div>Loading...</div>,
loginOptions: {
authorizationParams: {
invitation: searchParams.get("invitation") ?? undefined,
organization: searchParams.get("organization") ?? undefined
}
}
});
return <Component />;
};
This custom withUserAuthenticationRequired HOC retrieves the query params using useSearchParams and injects them into the loginOptions prop of withAuthenticationRequired. The ?? undefined ensures these parameters are only included if they exist in the URL.
Happy engineering!