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

789
Visualizações
Prevent going to the previous page on browser back button

I have a Next.js / React.js project I'm working on and I'm trying to redirect to a certain page when browser's back button is clicked. My approach is as follows

useEffect(() => {
    Router?.beforePopState(({ as }) => {
        if (as !== router.asPath) {
            handleRouteChange({ toHref: getRoutingPath('HOME') }, Router.push);
        }
        return true;
    });
        
    return () => {
        Router?.beforePopState(() => true);
    };
}, [dispatch, router]);

And this code works. When I click the back button, it takes me to the home page as intended.

But the issue is, when I click on the back button, it takes me to the previous page for a second and then redirects to the home page. How can I prevent going to the previous page at all?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can return false from the beforePopState callback to disable Next.js handling the routing automatically and handle it yourself.

From the router.beforePopState documentation:

If cb returns false, the Next.js router will not handle popstate, and you'll be responsible for handling it in that case. See Disabling file-system routing.

useEffect(() => {
    router.beforePopState(({ as }) => {
        if (as !== router.asPath) {
            handleRouteChange({ toHref: getRoutingPath('HOME') }, Router.push);
            return false;
        }
        return true;
    });
    
    return () => {
        router.beforePopState(() => true);
    };
}, [router]);
about 4 years ago · Santiago Trujillo 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