import type { Metadata } from 'next'; import { notFound } from 'next/navigation'; import { Link } from '@/core/lib/navigation'; import type { PublicMetafieldDefinition } from 'brainerce'; import { getServerClient } from '@/core/lib/brainerce.server'; import { getRegionId } from '@/core/lib/region.server'; import { buildProductQuery, isFilterableMetafield, listingSignature, paramSourceFromObject, readListingUrlState, selectedMetafieldsKey, } from '@/core/lib/listing-query'; import { localePath } from '@/core/lib/locale-path'; import { getServerNamespace } from '@/core/lib/server-messages'; import { ListingSeedProvider, type ListingSeed } from '@/core/providers/listing-seed'; import { ProductListing } from '@/ui/product/product-listing'; type Props = { // `locale` exists only on a multi-language storefront (the `[locale]` segment). params: Promise<{ locale?: string }>; searchParams: Promise>; }; // Title and description come from the message files in the request locale. They // used to be a scaffold-time ternary on `language === 'he'`, which gave every // visitor of a multi-language store the default language's copy. // // Canonical: each page of the catalog is its own canonical (`?page=2` is not a // duplicate of page 1, and pointing it there tells Google to drop its products). // A filtered, searched or sorted view is a permutation of the same catalog and // canonicalizes to the plain listing. The locale prefix is added only for a // non-default locale; the middleware 308-redirects `/{default}/x` to `/x`. export async function generateMetadata({ params, searchParams }: Props): Promise { const { locale } = await params; const state = readListingUrlState(paramSourceFromObject(await searchParams)); const seo = await getServerNamespace('seo', locale); const title = seo.products ?? ''; const description = seo.productsDescription ?? ''; const base = localePath(locale, '/products'); const isPlainListing = !state.search && !state.categoryId && !state.brandId && !state.tagId && !state.minPrice && !state.maxPrice && state.sortIndex === 0 && Object.keys(state.metafields).length === 0; const canonical = isPlainListing && state.page > 1 ? `${base}?page=${state.page}` : base; return { title, description, alternates: { canonical }, // `openGraph` replaces the root layout's object wholesale rather than // merging into it; the store name is added by the title template. openGraph: { title, description, type: 'website' }, }; } /** * The catalog page. A SERVER component that fetches the page the URL asks for * (search, category, brand, tag, price range, sort, custom-field facets and * `?page=`) and hands it to the client listing, so the initial HTML carries real * products for every one of those URLs. It used to be `'use client'` end to end: * the server sent a spinner and the browser fetched, so a crawler that does not * run JavaScript saw an empty page at the second most important URL on the site. * * Shopper interaction after the first render is unchanged: filters push a new * URL, "Load more" appends, and the client hook fetches for anything the seed * does not answer. */ export default async function ProductsPage({ params, searchParams }: Props) { const { locale } = await params; const query = await searchParams; const state = readListingUrlState(paramSourceFromObject(query)); let seed: ListingSeed | null = null; try { const client = await getServerClient(locale); const regionId = await getRegionId(); // Facets only filter when the store exposes them as filterable, so the // definitions are needed to turn `mf_` into a query, and only when the // URL selected one. let metafieldDefs: PublicMetafieldDefinition[] = []; if (Object.keys(state.metafields).length > 0) { const defs = await client.getPublicMetafieldDefinitions(); metafieldDefs = defs.definitions.filter(isFilterableMetafield); } const metafieldsKey = selectedMetafieldsKey( state.metafields, metafieldDefs.map((d) => d.key) ); const opts = { regionId, metafieldsKey, page: state.page }; const result = await client.getProducts(buildProductQuery(state, opts)); seed = { products: result.data, page: state.page, totalPages: result.meta.totalPages, total: result.meta.total, signature: listingSignature(state, opts), metafieldDefs, }; } catch { // Non-fatal: the client hook fetches the same query itself. seed = null; } // No `` around the listing, deliberately. The listing reads the URL // through `useSearchParams`, which only needs a boundary when a route is // prerendered statically; this page is dynamic (it reads `searchParams`), so // there is nothing to bail out of. The wrapper was not neutral: in the base // design it made the server flush a spinner fallback and stream the real grid // after it, which is the opposite of what the seed is for. // A page past the end of the result set is not a page. Rendering it empty with // its own canonical hands crawlers an endless supply of soft-404 URLs // (`?page=99`, `?page=100`, ...). Only when the query answered, never when the // fetch failed (then `seed` is null and the client hook tries again). if (seed && state.page > 1 && seed.products.length === 0) notFound(); // Crawlable pagination. "Load more" is a button, so without real links nothing // on the page leads to `?page=2`, and a crawler that does not run JavaScript // can only reach page 2+ of the catalog by guessing the URL. These are plain // `` links rendered on the server, keeping whatever filters the shopper has // chosen; shoppers keep using "Load more". const pageHref = (target: number): string => { const params = new URLSearchParams(); for (const [key, value] of Object.entries(query)) { const first = Array.isArray(value) ? value[0] : value; if (first !== undefined && key !== 'page') params.set(key, first); } if (target > 1) params.set('page', String(target)); const qs = params.toString(); return `${localePath(locale, '/products')}${qs ? `?${qs}` : ''}`; }; const strings = seed && seed.totalPages > 1 ? await getServerNamespace('seo', locale) : null; return ( <> {seed && strings ? ( ) : null} ); }