'How to handle Deep Linking with Auth0-react SDK

I'm using Auth0-react sdk, which is the newer version of the react-auth0-spa.js.

I'm trying to redirect the user to the original URL enter in the browser before they get redirected to the Auth0 login.

The process would be the following:

  1. User enters a specific url in the browser (eg: https://example.com/products/list/items) and presses enter
  2. The website redirects the user to the Auth0 domain to login
  3. User enters their credential and successfully login
  4. At this stage, the user should be redirected to the https://example.com/products/list/items instead of just going to https://example.com

I followed the instructions to set the SDK app from the official Auth0 website

Here is my code:

import { Auth0Provider } from "@auth0/auth0-react";

ReactDOM.render(
  <Auth0Provider
    domain="YOUR_DOMAIN"
    clientId="YOUR_CLIENT_ID"
    redirectUri={window.location.origin}
    audience="YOUR_AUDIENCE_URL"
  >
    <App />
  </Auth0Provider>,
  document.getElementById("root")

While the documentation uses an example with a clickable button to login, I have a component which triggers the login function:

import { useAuth0 } from '@auth0/auth0-react';

const LogIn = () => {
  const { loginWithRedirect } = useAuth0();

  React.useEffect(() => {
    loginWithRedirect()
  })

  return false;
};

export default LogIn;

Reading some docs, I've found handleRedirectCallback, which in theory should be available as a method within useAuth0. At the moment, the above login, doesn't do the deep linking redirect and I don't see an example for the auth0-react on how to use handleRedirectCallback. I was wondering if someone can suggest what I can use with the React SDK.

Thanks in advance. Joe



Solution 1:[1]

It might not be what you're looking for, but the answer in this question helped me with a similar problem (I got There are no query params available for parsing. when using this callback handler).

Instead of telling Auth0 to navigate to a /callback route and handle the redirection there (which caused me the no query params issue), the solution is to add a callback function as a onRedirectCallback prop to the Auth0Provider component, which will navigate to wherever you want. For example:

  const onRedirectCallback = appState => {
    navigate(appState?.returnTo || window.location.pathname, { replace: true });
  };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1