#OAuth login flow with TanStack router

4 messages · Page 1 of 1 (latest)

sullen crescent
#

I'm trying to implement OAuth and I want to understand the correct pattern/how to approach this in the context of the router.

I have an AuthProvider component wrapping the router:

function InnerApp({ router }: AppProps) {
    const auth = useAuth();
    return (
        <>
            <RouterProvider router={router} context={{ auth }} />
        </>
    );
}

const App = ({ router }: AppProps): FunctionComponent => {
    return (
        <AuthProvider>
            <QueryClientProvider client={queryClient}>
                <InnerApp router={router} />
            </QueryClientProvider>
        </AuthProvider>
    );
};

The AuthProvider contains an isAuthenticated value, also it internally contains functions to do the following: 1. Redirect to the external OAuth Login Page. 2. Detect whether the user is authenticated. 3. Handle the redirect back from the OAuth callback (save the token, etc).

My question is: where should I be calling those functions from? Should they be in an effect hook in the AuthProvider component, in the beforeLoad callback for all my routes, or somewhere else?

#

it feels pointless to have every beforeLoad say:

if (!context.auth.isAuthenticated) {
  context.auth.redirectToSignIn();
}

I could put this in an effect hook in the AuthProvider, put I would be dependent on window.location and not using the router, because the provider exists outsider of the router

rustic raft
#

You can setup a layout/pathless route that wraps all your "authenticated" routes. The beforeLoad check can then happen in this one layout route.

This is what we've done in the "authenticated-routes" example.