fix: improve locale detection in 404 page to match middleware logic

- Add detectLocale function that checks URL path first, then cookie, then accept-language header
- Use getLocaleFromPath helper to extract locale from URL
- Import LOCALE_COOKIE constant for consistency
- All product links now use detected locale for proper routing
This commit is contained in:
Unchained
2026-03-28 22:56:17 +02:00
parent 5b33ede980
commit f3932ff7e7

View File

@@ -1,33 +1,61 @@
import { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { getProducts, getProductImage, getProductPrice } from "@/lib/saleor";
import { getSaleorLocale, isValidLocale, DEFAULT_LOCALE } from "@/lib/i18n/locales";
import type { Locale } from "@/lib/i18n/locales";
import {
getSaleorLocale,
isValidLocale,
DEFAULT_LOCALE,
getLocaleFromPath,
LOCALE_COOKIE,
type Locale
} from "@/lib/i18n/locales";
import type { Product } from "@/types/saleor";
import Link from "next/link";
import Image from "next/image";
import { Star, ArrowRight } from "lucide-react";
import { headers } from "next/headers";
import { cookies } from "next/headers";
export const metadata: Metadata = {
title: "Page Not Found | ManoonOils",
description: "Discover our bestselling natural oils for hair and skin care.",
};
function detectLocale(pathname: string, cookieLocale: string | undefined, acceptLanguage: string): Locale {
// First, check if URL has a locale prefix
const localeFromPath = getLocaleFromPath(pathname);
if (pathname.match(/^\/(sr|en|de|fr)/)) {
return localeFromPath as Locale;
}
// Second, check cookie
if (cookieLocale && isValidLocale(cookieLocale)) {
return cookieLocale;
}
// Third, check accept-language header
if (acceptLanguage.includes("en")) {
return "en";
}
// Default to Serbian
return DEFAULT_LOCALE;
}
export default async function NotFoundPage() {
// Get locale from URL path
const headersList = await headers();
const pathname = headersList.get("x-invoke-path") || headersList.get("x-matched-path") || "/";
const acceptLanguage = headersList.get("accept-language") || "";
// Extract locale from path (e.g., /en/products → en, /sr/products → sr)
const pathSegments = pathname.split("/").filter(Boolean);
const potentialLocale = pathSegments[0];
const validLocale = isValidLocale(potentialLocale) ? potentialLocale : DEFAULT_LOCALE;
const cookieStore = await cookies();
const cookieLocale = cookieStore.get(LOCALE_COOKIE)?.value;
const validLocale = detectLocale(pathname, cookieLocale, acceptLanguage);
const t = await getTranslations({ locale: validLocale, namespace: "NotFound" });
const productReviewT = await getTranslations({ locale: validLocale, namespace: "ProductReviews" });
const saleorLocale = getSaleorLocale(validLocale as Locale);
const saleorLocale = getSaleorLocale(validLocale);
// Fetch products
let products: Product[] = [];