React app redirects to correct url after login but component stays the same

I have a problem with redirecting users to the intended component after login with auth0

When I click on the button to go to the library, the library is a protected component, so it goes to the login page, after login it sends me back to my app, and the route is http://localhost:5173/library BUT the rendered component is LandingPage

Ask me any questions, as I’m desperate, trying to solve it for too long

my main.js

import { createRoot } from "react-dom/client";
import "@/styles/index.scss";
import App from "./App.tsx";
import { Auth0Provider } from "@auth0/auth0-react";

createRoot(document.getElementById("root")!).render(
  <Auth0Provider
    domain={import.meta.env.VITE_AUTH0_DOMAIN}
    clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
    authorizationParams={{
      redirect_uri: window.location.origin + window.location.pathname,
      audience: import.meta.env.VITE_AUTH0_AUDIENCE,
    }}
    cacheLocation="localstorage"
  >
    <App />
  </Auth0Provider>
);

ProtectedComponent.ts

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

const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  const ProtectedComponent = withAuthenticationRequired(() => <>{children}</>, {
    returnTo: window.location.origin + window.location.pathname,
  });

  return <ProtectedComponent />;
};

export default ProtectedRoute;

App.tsx

function App() {
  return (
    <Router>
      <Routes>
        <Route
          path="/quiz-editor"
          element={
            <ProtectedRoute>
              <QuizEditor />
            </ProtectedRoute>
          }
        />
        <Route path="/" element={<LandingPage />} />
        <Route
          path="/library"
          element={
            <ProtectedRoute>
              <Library />
            </ProtectedRoute>
          }
        />
      </Routes>
    </Router>
  );
}

Hi @grin.mihail,

Welcome to the Auth0 Community!

Can you try using ProtectedRoute in this way:

export default function Routing() {
  return (
    <Routes>
      <Route path="/library" element={<ProtectedRoute component={Library} />} />
    </Routes>
  );
}

I set this up on my React application and ran into issues with the following:

element={
            <ProtectedRoute>
              <Library />
            </ProtectedRoute>
          }

Please see here for more information on adding route guards to React: React Authentication By Example: Using React Router 6

I look forward to your reply!

Thanks,

Mary Beth

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.