Next.js Discord

Discord Forum

Help - How to Intercept Browser Back Button Next14+

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
Hello. How can I intercept the browser's back button? So that I can redirect the user to a specific page (another link) instead of going back to the previous page of my application.

Example: I have an application with two pages, home and about. I navigate from home to about. Now on About, the only way to go back is by pressing the browser's back button. I want to intercept this button, so that when clicked, the user is redirected to Google...

"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";

export default function TestComponent() {
  const router = useRouter();
  useEffect(() => {
    window.onpopstate = function () {
      router.push("https://www.google.com.br");
    };
    return () => {
      null;
    };
  });

  return (
    <div className="w-full h-screen">
      <h1 className="text-2xl font-bold text-black mx-auto">
        Go back from this page.
      </h1>
    </div>
  );
}


The code above isn't working. It works in npm run dev, but when I host the application somewhere like on netlify, the window.onpopstate stops working.

How can I work around this issue?

0 Replies