Install the Auth React SDK on the terminal
npm install @auth0/auth0-react
Create an auth0-provider-with-navigate.js
file in the src folder.
Add the following code.
import { Auth0Provider } from "@auth0/auth0-react";
import React from "react";
import { useNavigate } from "react-router-dom";
export const Auth0ProviderWithNavigate = ({ children }) => {
const navigate = useNavigate();
const domain = process.env.REACT_APP_AUTH0_DOMAIN;
const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID;
const redirectUri = process.env.REACT_APP_AUTH0_CALLBACK_URL;
const onRedirectCallback = (appState) => {
navigate(appState?.returnTo || window.location.pathname);
};
if (!(domain && clientId && redirectUri)) {
return null;
}
return (
<Auth0Provider
domain={domain}
clientId={clientId}
authorizationParams={{
redirect_uri: redirectUri,
}}
onRedirectCallback={onRedirectCallback}
>
{children}
</Auth0Provider>
);
};
Wrap the Auth0ProviderWithNavigate
component around the App
component inside of index.js
to give it access to the Auth0Context
.
Auth0ProviderWithNavigate
needs the BrowserRouter
component from React Router to be its parent, grandparent, or great-great-great-grandparent.