From 7effc29110ff90b921a5d435df1a9338534632f0 Mon Sep 17 00:00:00 2001 From: Rodrigo Azevedo Date: Wed, 25 Jun 2025 10:24:07 -0300 Subject: [PATCH] feat: add support for pre-configured Auth0Client instance in Auth0Provider --- __tests__/auth-provider.test.tsx | 16 ++++++++++++++++ src/auth0-provider.tsx | 30 +++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/__tests__/auth-provider.test.tsx b/__tests__/auth-provider.test.tsx index 0ec66d3c..17dfa70d 100644 --- a/__tests__/auth-provider.test.tsx +++ b/__tests__/auth-provider.test.tsx @@ -60,6 +60,22 @@ describe('Auth0Provider', () => { }); }); + it('should support Auth0Client instance', async () => { + const opts = { + clientId: 'foo', + domain: 'bar', + client: clientMock, + }; + const wrapper = createWrapper(opts); + renderHook(() => useContext(Auth0Context), { + wrapper, + }); + + await waitFor(() => { + expect(Auth0Client).not.toHaveBeenCalled(); + }); + }); + it('should support redirectUri', async () => { const warn = jest.spyOn(console, "warn").mockImplementation(() => undefined); const opts = { diff --git a/src/auth0-provider.tsx b/src/auth0-provider.tsx index ac4e4f1c..f680cbfc 100644 --- a/src/auth0-provider.tsx +++ b/src/auth0-provider.tsx @@ -84,6 +84,33 @@ export interface Auth0ProviderOptions extends Auth0Cl * For a sample on using multiple Auth0Providers review the [React Account Linking Sample](https://github.com/auth0-samples/auth0-link-accounts-sample/tree/react-variant) */ context?: React.Context>; + /** + * A pre-configured Auth0Client instance to use for authentication operations. + * + * When provided, this client will be used instead of creating a new one internally. + * This is useful for: + * - Sharing a single Auth0Client instance across multiple components + * - Using a client with custom configuration or advanced setup + * - Testing scenarios where you need to inject a mock client + * - Scenarios where you need fine-grained control over client initialization timing + * + * If not provided, the Auth0Provider will automatically create a new Auth0Client + * instance using the other configuration options passed to the provider. + * + * @example + * ```tsx + * const customClient = new Auth0Client({ + * domain: 'your-domain.auth0.com', + * clientId: 'your-client-id', + * // ... other options + * }); + * + * + * + * + * ``` + */ + client?: Auth0Client; } /** @@ -138,10 +165,11 @@ const Auth0Provider = (opts: Auth0ProviderOptions new Auth0Client(toAuth0ClientOptions(clientOpts)) + () => providedClient ?? new Auth0Client(toAuth0ClientOptions(clientOpts)) ); const [state, dispatch] = useReducer(reducer, initialAuthState as AuthState); const didInitialise = useRef(false);