Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
Flash of protected route's content with React Router 6

When using React Router 6 to create a "protected route", I see the protected page's content flash briefly before the redirect to the login page.

I would assume this must be a well-known problem. Is there a solution for this?

ProtectedRoute:

const ProtectedRoute = ({
    redirectPath = '/login',
    children
}) => {

    const { user } = UserAuth();

    if (!user) {
        return <Navigate to={redirectPath} replace />;
    }

    return children
        ? children
        : <Outlet />;
};

export default ProtectedRoute;

AppRouter:

const AppRouter = () => (
    <Routes>

        <Route path="/" element={<LoginPage />} />
        <Route path="login" element={<LoginPage />}/>

        <Route element={<ProtectedRoute />} >
            <Route path="account" element={<AccountPage />} />
        </Route>

    </Routes>
);

export default AppRouter;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would assume UserAuth() do some asynchronous tasks. In witch it's normal get this behaviour. You could use a loader. I'm would assume you could get one from UserAuth() while executing the code for authentication. Like so:

const ProtectedRoute = ({
    redirectPath = '/login',
    children
}) => {

    const { user, loading } = UserAuth();
    
    if (loading) return <div>Loading...</div>

    if (!user) {
        return <Navigate to={redirectPath} replace />;
    }

    return children
        ? children
        : <Outlet />;
};

export default ProtectedRoute;
about 4 years ago · Juan Pablo Isaza Relatório

0

Issue

The issue is that to provide proper UI/UX to the user you need 3 states (i.e. authenticated, unauthenticated, indeterminant) instead of 2 (authenticated and unauthenticated). With only 2 states then the initial authentication value and branching logic matches one or the other and incorrectly "leaks" out the protected content for a moment or prematurely redirects to a login route.

Solution

Use an indeterminant user value or loading state to indicate to the protected route component that it shouldn't render the protected content or redirect yet.

Using third indeterminant "state".

For example, if an authenticated user value is a user object and an unauthenticated user value is null, then use undefined as the indeterminant value and conditionally render null or some loading indicator while the auth state is resolved.

const ProtectedRoute = ({
  redirectPath = '/login',
  children
}) => {
  const { user } = userAuth();

  if (user === undefined) {
    return null; // or loading spinner, etc
  }

  if (!user) {
    return <Navigate to={redirectPath} replace />;
  }

  return children
    ? children
    : <Outlet />;
};

Using pending/loading "state".

Sometimes it is useful to just add a loading state to the userAuth state. The logic is nearly identical.

const ProtectedRoute = ({
  redirectPath = '/login',
  children
}) => {
  const { isLoading, user } = userAuth();

  if (isLoading) {
    return null; // or loading spinner, etc
  }

  if (!user) {
    return <Navigate to={redirectPath} replace />;
  }

  return children
    ? children
    : <Outlet />;
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda