From 115afd4275482eecdba7e10c6f2264dfaa55485f Mon Sep 17 00:00:00 2001 From: Leander Furumo Date: Fri, 30 Oct 2026 22:57:28 +0100 Subject: [PATCH] Make the Back button aware of client-side navigation document.referrer only changes on full page loads, so the button sent visitors to the home page instead of back after navigating within the site. Use the Navigation API's canGoBack, which only considers this site's history entries, and keep the referrer check as a fallback. Co-Authored-By: Claude Opus 5.5 --- src/components/ui/back.tsx | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/components/ui/back.tsx b/src/components/ui/back.tsx index f4a73c7..eb5380d 100644 --- a/src/components/ui/back.tsx +++ b/src/components/ui/back.tsx @@ -1,27 +1,32 @@ "use client" -import { useLocale, useTranslations } from "next-intl" -import { useRouter } from "next/navigation" +import { useTranslations } from "next-intl" import { FaArrowLeft } from "react-icons/fa" +import { useRouter } from "@/i18n/navigation" + import * as styles from "./back.module.css" +// document.referrer only reflects the last full page load, so it misses +// client-side navigations within the site. Only used where the Navigation +// API isn't supported +const cameFromThisSite = () => + document.referrer !== "" && + new URL(document.referrer).origin === window.location.origin + const Back = () => { - const locale = useLocale() const router = useRouter() const t = useTranslations("buttons") const handleBack = () => { - const currentDomain = window.location.hostname - const referrer = document.referrer + // The Navigation API only lists this site's own history entries, so + // canGoBack is true exactly when the previous page was on this site + const canGoBack = window.navigation?.canGoBack ?? cameFromThisSite() - const isSameDomain = - referrer && new URL(referrer).hostname === currentDomain - - if (window.history.length > 1 && isSameDomain) { - window.history.back() + if (canGoBack) { + router.back() } else { - router.push(`/${locale}`) + router.push("/") } }