-
Notifications
You must be signed in to change notification settings - Fork 290
feat: add useAuth0Suspense hook for handling auth loading state with React 19+ #1184
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
7eeb79a
acc9ba4
44b10e2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| import { Auth0Client } from '@auth0/auth0-spa-js'; | ||
| import '@testing-library/jest-dom'; | ||
| import { | ||
| act, | ||
| render, | ||
| renderHook, | ||
| screen, | ||
| waitFor, | ||
| } from '@testing-library/react'; | ||
| import React, { Component, ReactNode, Suspense } from 'react'; | ||
| import { Auth0Provider } from '../src'; | ||
| import useAuth0Suspense from '../src/use-auth0-suspense'; | ||
| import { defer } from './helpers'; | ||
|
|
||
| const clientMock = jest.mocked(new Auth0Client({ clientId: '', domain: '' })); | ||
|
|
||
| class ErrorBoundary extends Component< | ||
| { children: ReactNode }, | ||
| { error: Error | null } | ||
| > { | ||
| state = { error: null as Error | null }; | ||
| static getDerivedStateFromError(error: Error) { | ||
| return { error }; | ||
| } | ||
| render() { | ||
| return this.state.error ? ( | ||
| <div>boundary: {this.state.error.message}</div> | ||
| ) : ( | ||
| this.props.children | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| function Greeting() { | ||
| const { user, isAuthenticated } = useAuth0Suspense(); | ||
| return <div>{isAuthenticated ? `Hello ${user?.name}` : 'Please log in'}</div>; | ||
| } | ||
|
|
||
| const renderWithProvider = async (child: ReactNode) => | ||
| act(async () => { | ||
| render( | ||
| <Auth0Provider clientId="__test_client_id__" domain="__test_domain__"> | ||
| <ErrorBoundary> | ||
| <Suspense fallback={<div>loading</div>}>{child}</Suspense> | ||
| </ErrorBoundary> | ||
| </Auth0Provider> | ||
| ); | ||
| }); | ||
|
|
||
| describe('useAuth0Suspense', () => { | ||
| afterEach(() => { | ||
| window.history.pushState({}, document.title, '/'); | ||
| }); | ||
|
|
||
| it('shows the Suspense fallback while init is pending, then the content', async () => { | ||
| const userDefer = defer<{ name: string }>(); | ||
| clientMock.checkSession.mockResolvedValue(undefined); | ||
| clientMock.getUser.mockReturnValue(userDefer.promise as never); | ||
|
|
||
| await renderWithProvider(<Greeting />); | ||
|
|
||
| // Still initializing -> fallback | ||
| expect(screen.getByText('loading')).toBeInTheDocument(); | ||
|
|
||
| userDefer.resolve({ name: 'Bob' }); | ||
|
|
||
| await waitFor(() => | ||
| expect(screen.getByText('Hello Bob')).toBeInTheDocument() | ||
| ); | ||
| }); | ||
|
|
||
| it('throws init errors to the nearest Error Boundary', async () => { | ||
| clientMock.checkSession.mockRejectedValueOnce({ | ||
| error: '__test_error__', | ||
| error_description: '__test_error_description__', | ||
| }); | ||
|
|
||
| await renderWithProvider(<Greeting />); | ||
|
|
||
| await waitFor(() => | ||
| expect( | ||
| screen.getByText(/boundary: .*__test_error_description__/) | ||
| ).toBeInTheDocument() | ||
| ); | ||
| }); | ||
|
|
||
| it('throws redirect-callback init errors to the nearest Error Boundary', async () => { | ||
| // Presence of code/state in the URL makes hasAuthParams() true, so init | ||
| // takes the handleRedirectCallback branch instead of checkSession. | ||
| window.history.pushState( | ||
| {}, | ||
| document.title, | ||
| '/?code=__test_code__&state=__test_state__' | ||
| ); | ||
| clientMock.handleRedirectCallback.mockRejectedValueOnce({ | ||
| error: '__redirect_error__', | ||
| error_description: '__redirect_error_description__', | ||
| }); | ||
|
|
||
| await renderWithProvider(<Greeting />); | ||
|
|
||
| await waitFor(() => | ||
| expect( | ||
| screen.getByText(/boundary: .*__redirect_error_description__/) | ||
| ).toBeInTheDocument() | ||
| ); | ||
| }); | ||
|
|
||
| it('returns the auth methods, omitting isLoading and _initPromise', async () => { | ||
| clientMock.checkSession.mockResolvedValue(undefined); | ||
| clientMock.getUser.mockResolvedValue({ name: 'Bob' }); | ||
|
|
||
| let captured: Record<string, unknown> | undefined; | ||
| function Capture() { | ||
| captured = useAuth0Suspense() as unknown as Record<string, unknown>; | ||
| return <div>captured</div>; | ||
| } | ||
|
|
||
| await renderWithProvider(<Capture />); | ||
| await waitFor(() => | ||
| expect(screen.getByText('captured')).toBeInTheDocument() | ||
| ); | ||
|
|
||
| expect(captured).not.toHaveProperty('isLoading'); | ||
| expect(captured).not.toHaveProperty('_initPromise'); | ||
| expect(captured).toHaveProperty('error'); | ||
| expect(typeof captured!.loginWithRedirect).toBe('function'); | ||
| }); | ||
|
|
||
| it('throws a clear error when used outside an Auth0Provider', () => { | ||
| expect(() => renderHook(() => useAuth0Suspense())).toThrowError( | ||
| /must be used within/ | ||
| ); | ||
| }); | ||
|
|
||
| it('throws a clear error when React.use is unavailable', async () => { | ||
| jest.resetModules(); | ||
| jest.doMock('react', () => { | ||
| const actual = jest.requireActual('react'); | ||
| return { ...actual, use: undefined }; | ||
| }); | ||
| const { default: hook } = await import('../src/use-auth0-suspense'); | ||
| expect(() => hook()).toThrowError(/requires React 19/); | ||
| jest.dontMock('react'); | ||
| jest.resetModules(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('useAuth0Suspense exports', () => { | ||
| it('is exported from the package root', async () => { | ||
| const pkg = await import('../src'); | ||
| expect(typeof pkg.useAuth0Suspense).toBe('function'); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -189,6 +189,18 @@ const Auth0Provider = <TUser extends User = User>(opts: Auth0ProviderOptions<TUs | |
| () => providedClient ?? new Auth0Client(toAuth0ClientOptions(clientOpts)) | ||
| ); | ||
| const [state, dispatch] = useReducer(reducer<TUser>, initialAuthState as AuthState<TUser>); | ||
| const [initDeferred] = useState(() => { | ||
| let resolve!: () => void; | ||
| let reject!: (error: Error) => void; | ||
| const promise = new Promise<void>((res, rej) => { | ||
| resolve = res; | ||
| reject = rej; | ||
| }); | ||
| // Avoid unhandled-rejection warnings when no one is consuming the promise | ||
| // (i.e. useAuth0Suspense is not used). useAuth0Suspense attaches its own handler via use(). | ||
| promise.catch(() => undefined); | ||
| return { promise, resolve, reject }; | ||
| }); | ||
| const didInitialise = useRef(false); | ||
|
|
||
| const handleError = useCallback((error: Error) => { | ||
|
|
@@ -217,11 +229,14 @@ const Auth0Provider = <TUser extends User = User>(opts: Auth0ProviderOptions<TUs | |
| user = await client.getUser(); | ||
| } | ||
| dispatch({ type: 'INITIALISED', user }); | ||
| initDeferred.resolve(); | ||
| } catch (error) { | ||
| handleError(loginError(error)); | ||
| const err = loginError(error); | ||
| handleError(err); | ||
| initDeferred.reject(err); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Once this rejects, the promise is settled for the provider's whole lifetime, so |
||
| } | ||
| })(); | ||
| }, [client, onRedirectCallback, skipRedirectCallback, handleError]); | ||
| }, [client, onRedirectCallback, skipRedirectCallback, handleError, initDeferred]); | ||
|
|
||
| const loginWithRedirect = useCallback( | ||
| (opts?: RedirectLoginOptions): Promise<void> => { | ||
|
|
@@ -480,6 +495,7 @@ const Auth0Provider = <TUser extends User = User>(opts: Auth0ProviderOptions<TUs | |
| mfa, | ||
| passkey, | ||
| myAccount, | ||
| _initPromise: initDeferred.promise, | ||
| }; | ||
| }, [ | ||
| state, | ||
|
|
@@ -503,6 +519,7 @@ const Auth0Provider = <TUser extends User = User>(opts: Auth0ProviderOptions<TUs | |
| mfa, | ||
| passkey, | ||
| myAccount, | ||
| initDeferred, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Listing the whole object |
||
| ]); | ||
|
|
||
| return <context.Provider value={contextValue}>{children}</context.Provider>; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,10 @@ export { | |
| ConnectedAccount | ||
| } from './auth0-provider'; | ||
| export { default as useAuth0 } from './use-auth0'; | ||
| export { | ||
| default as useAuth0Suspense, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Small thing — can we add |
||
| Auth0SuspenseContextInterface, | ||
| } from './use-auth0-suspense'; | ||
| export { default as withAuth0, WithAuth0Props } from './with-auth0'; | ||
| export { | ||
| default as withAuthenticationRequired, | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,62 @@ | ||||||||||||||||
| // Namespace import: `use` only exists as a named export from React 19, so | ||||||||||||||||
| // `import { use }` fails at link time for React 16-18 consumers even if they | ||||||||||||||||
| // never call this hook. Property access stays late-bound. | ||||||||||||||||
| import * as React from 'react'; | ||||||||||||||||
| import { User } from '@auth0/auth0-spa-js'; | ||||||||||||||||
| import Auth0Context, { Auth0ContextInterface } from './auth0-context'; | ||||||||||||||||
|
|
||||||||||||||||
| /** | ||||||||||||||||
| * The value returned by `useAuth0Suspense`: the full `useAuth0` interface minus | ||||||||||||||||
| * `isLoading` and the internal `_initPromise`. `error` is | ||||||||||||||||
| * retained for post-init failures such as `loginWithPopup`. | ||||||||||||||||
| */ | ||||||||||||||||
| export type Auth0SuspenseContextInterface<TUser extends User = User> = Omit< | ||||||||||||||||
| Auth0ContextInterface<TUser>, | ||||||||||||||||
| 'isLoading' | '_initPromise' | ||||||||||||||||
| >; | ||||||||||||||||
|
coderabbitai[bot] marked this conversation as resolved.
|
||||||||||||||||
|
|
||||||||||||||||
| /** | ||||||||||||||||
| * ```jsx | ||||||||||||||||
| * <Suspense fallback={<Spinner />}> | ||||||||||||||||
| * <Profile /> | ||||||||||||||||
| * </Suspense> | ||||||||||||||||
| * | ||||||||||||||||
| * function Profile() { | ||||||||||||||||
| * const { user, isAuthenticated } = useAuth0Suspense(); | ||||||||||||||||
| * return isAuthenticated ? <p>Hello {user.name}</p> : <p>Please log in</p>; | ||||||||||||||||
| * } | ||||||||||||||||
| * ``` | ||||||||||||||||
| * | ||||||||||||||||
| * Suspense-enabled variant of `useAuth0`. Suspends the component until Auth0 | ||||||||||||||||
| * initialization completes (letting the nearest `<Suspense>` fallback render), | ||||||||||||||||
| * and throws initialization errors so the nearest Error Boundary can handle | ||||||||||||||||
| * them. Requires React 19 or later. | ||||||||||||||||
| * | ||||||||||||||||
| * TUser is an optional type param to provide a type to the `user` field. | ||||||||||||||||
| */ | ||||||||||||||||
| const useAuth0Suspense = <TUser extends User = User>( | ||||||||||||||||
| context = Auth0Context | ||||||||||||||||
| ): Auth0SuspenseContextInterface<TUser> => { | ||||||||||||||||
| if (typeof React.use !== 'function') { | ||||||||||||||||
| throw new Error( | ||||||||||||||||
| 'useAuth0Suspense requires React 19 or later (React.use is unavailable).' | ||||||||||||||||
| ); | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| const ctx = React.useContext(context) as Auth0ContextInterface<TUser>; | ||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Normal react hooks like |
||||||||||||||||
|
|
||||||||||||||||
| if (!ctx._initPromise) { | ||||||||||||||||
| throw new Error( | ||||||||||||||||
| 'useAuth0Suspense must be used within an <Auth0Provider>.' | ||||||||||||||||
| ); | ||||||||||||||||
|
Comment on lines
+48
to
+51
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This outside guard works today but it seems fragile. It relies on
Comparing this with how |
||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| // Suspends until the init promise resolves; re-throws if it rejected. | ||||||||||||||||
| React.use(ctx._initPromise); | ||||||||||||||||
|
|
||||||||||||||||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||||||||||||||||
| const { isLoading, _initPromise, ...rest } = ctx; | ||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The rest-spread returns a new object each render, whereas
Suggested change
|
||||||||||||||||
| return rest; | ||||||||||||||||
| }; | ||||||||||||||||
|
|
||||||||||||||||
| export default useAuth0Suspense; | ||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tiny nit, non-blocking — the trailing newline at EOF got dropped here, and there's an extra blank line in the TOC entry above. Kindly restore both.