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 <noreply@anthropic.com>
This commit is contained in:
leanderandClaude Opus 5.5 committed 2026-10-30 22:57:28 +01:00
1 parent 67641c5719
commit 115afd4275
1 file changed
+16 -11
+16 -11
View File
@@ -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("/")
}
}