Search code examples
routesgatsbyauth0

Login doesn't show up in Gatsby using Auth0, withAuthenticationRequired


I'm using Gatsby with auth0, and when I wrap a page with withAuthenticationRequired, then I get a blank page that says "Redirecting..."

import * as React from 'react';
import { withAuthenticationRequired } from '@auth0/auth0-react';


const UserIndexPage = () => {
  return (
    <div>
      User index page
    </div>
  );
};

export default withAuthenticationRequired(UserIndexPage, {
  onRedirecting: () => <div>Redirecting...</div>
});

The login screen doesn't come up, and the page is stuck with that Redirecting message

If I create a login button, without withAuthenticationRequired then the login screen comes up when I click it

const LoginButton = () => {
  const { loginWithRedirect } = useAuth0();
  return <button onClick={() => loginWithRedirect()}>Log In</button>;
};

Solution

  • Reviewing the new implementation released I believe the onRedirect callback should be managed by the Gatsby Browser (gatsby-browser.js):

    import React from 'react';
    import { Auth0Provider } from '@auth0/auth0-react';
    import { navigate } from 'gatsby';
    
    const onRedirectCallback = (appState) => {
      navigate(appState?.returnTo || '/', { replace: true });
    };
    
    export const wrapRootElement = ({ element }) => {
      return (
        <Auth0Provider
          domain="YOUR_AUTH0_DOMAIN"
          clientId="YOUR_AUTH0_CLIENT_ID"
          redirectUri={window.location.origin}
          onRedirectCallback={onRedirectCallback}
        >
          {element}
        </Auth0Provider>
      );
    };
    

    While in your UI view:

    import * as React from 'react';
    import { withAuthenticationRequired } from '@auth0/auth0-react';
    
    
    const UserIndexPage = () => {
      return (
        <div>
          User index page
        </div>
      );
    };
    
    export default withAuthenticationRequired(UserIndexPage);
    

    The idea is to wrap the component in the withAuthenticationRequired handler.

    The onRedirectCallback will use Gatsby's navigate function to return the user to the protected route after the login and will replace the URL to avoid odd behavior when the user's trying to move forward and backward.