I am encountering an issue in my Next.js application where using router.push with the { shallow: true } option is unexpectedly causing a page reload. That happens only on 404 Next.js Page when I use my redirect hook or just <Link/> component. I redirect from "/market/assets" to "/market/finance"
Redirect Hook
import { useRouter } from "next/router";
export default function useRedirect() {
const router = useRouter();
return (relativePath: string) =>
router.push(relativePath, undefined, { shallow: true });
}
Error404 Next.js page file
import { useEffect } from "react";
import { useRouter } from "next/router";
import AppLayout from "@/components/Layout/AppLayout";
import { REDIRECT_404_PATHS } from "@/constants/routes";
export default function Error404() {
const router = useRouter();
useEffect(() => {
if (REDIRECT_404_PATHS.includes(router.asPath))
router.push("/", undefined, { shallow: true });
}, [router]);
return (
<AppLayout>
We can’t find the page you are looking for.
</AppLayout>
);
}
I tried to: Changing approach of redirecting doesn't help Tracking 404 route on component and just replacing url doesn't help.