wealth/.claude/skills/front-end-architect/references/page-example.md

11 KiB

Page example: caches, page, and parts

A full page for b2c-b2b.md: device detection, caches, a server page loader, the page entrypoint with its status and JSON-LD, streamed parts, and query hydration. Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet. Otherwise copy the shape of an existing page. The page's rendering doc comes first (page-rendering.md).

platforms/<platform>/src/shared/utils/get-device.ts

import 'server-only';
import { headers } from 'next/headers';
import { userAgent } from 'next/server';

export type Device = 'mobile' | 'desktop';

// By device class only, never by isBot: content that differs for crawlers is cloaking.
// Googlebot Smartphone parses as 'mobile', so Google indexes the mobile template; tablets get desktop.
export function deviceFromHeaders(requestHeaders: Headers): Device {
  return userAgent({ headers: requestHeaders }).device.type === 'mobile' ? 'mobile' : 'desktop';
}

export async function getDevice(): Promise<Device> {
  return deviceFromHeaders(await headers());
}

Where the repo has a unit test runner, get-device.test.ts pins the mapping, so a parser upgrade can't send Googlebot Smartphone to the desktop template; otherwise the PR proposes the runner, which needs approval (refactoring.md). The test setup maps server-only to an empty module, as it does for every server-only test.

import { deviceFromHeaders } from './get-device';

const GOOGLEBOT_SMARTPHONE =
  'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.122 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
const GOOGLEBOT_DESKTOP =
  'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Chrome/141.0.7390.122 Safari/537.36';

describe('deviceFromHeaders', () => {
  it('sends Googlebot Smartphone to the mobile template, which Google indexes', () => {
    expect(deviceFromHeaders(new Headers({ 'user-agent': GOOGLEBOT_SMARTPHONE }))).toBe('mobile');
  });

  it('sends Googlebot Desktop and requests without a User-Agent to the desktop template', () => {
    expect(deviceFromHeaders(new Headers({ 'user-agent': GOOGLEBOT_DESKTOP }))).toBe('desktop');
    expect(deviceFromHeaders(new Headers())).toBe('desktop');
  });
});

platforms/<platform>/src/features/catalog/caches/products.ts

import 'server-only';
import { cache } from 'react';
import { productsRepository } from '../repositories/products';
import { RELATED_PRODUCTS_LIMIT } from './constants';

export const getProduct = cache((id: string) => productsRepository.get({ id }));

export const getRelatedProducts = cache((id: string) =>
  productsRepository.listRelated({ id, limit: RELATED_PRODUCTS_LIMIT }),
);

export const getProductReviews = cache((id: string, page: number) => productsRepository.listReviews({ id, page }));

platforms/<platform>/src/features/catalog/caches/server.ts

import 'server-only';

export { getProduct, getProductReviews, getRelatedProducts } from './products';

platforms/<platform>/src/server.ts

import 'server-only';

export { readOnServer } from './app/error-boundaries/read-on-server/server';
export { buildProductPageJsonLd } from './app/json-ld/server';
export { getProduct, getProductReviews, getRelatedProducts } from './features/catalog/caches/server';
export { getDevice } from './shared/utils/get-device';

apps/<app>/src/app/(shop)/product/[id]/page.tsx. A product page is an entity page: no loading.tsx sits above it, so its status is decided before the first byte (error-handling.md). generateMetadata and the page both call readProduct, which reads getProduct(id) through readOnServer, and the cache sends one request. A missing product answers 404, and a replaced one 308 to its replacement; replacedBy stands for the id of the product that replaces this one, which the back end sends. The page renders its JSON-LD from the same product, for an ok read only, before the template and in the first flush; buildProductPageJsonLd is in lib-json-ld.md. The seller page in error-handling-code.md has the same shape and explains the narrowing.

import { JsonLd } from '@project/island/primitives/json-ld/server';
import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { paths } from '@project/<platform>/app/navigation';
import { buildProductPageJsonLd, getDevice, getProduct, readOnServer } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { notFound, permanentRedirect } from 'next/navigation';
import { ProductDesktop } from './templates/product-desktop';
import { ProductMobile } from './templates/product-mobile';

type ProductPageProps = { params: Promise<{ id: string }> };

// Throws for a missing or replaced product; returns 'ok' or 'no-access'.
async function readProduct(id: string) {
  const product = await readOnServer(() => getProduct(id));
  if (product.status === 'not-found') notFound();
  if (product.status === 'ok' && product.data.replacedBy) permanentRedirect(paths.product(product.data.replacedBy));
  return product;
}

export async function generateMetadata({ params }: ProductPageProps): Promise<Metadata> {
  const { id } = await params;
  const product = await readProduct(id);
  if (product.status !== 'ok') return { robots: { index: false } };
  return {
    title: product.data.name,
    description: product.data.summary,
    alternates: { canonical: paths.product(product.data.id) },
  };
}

export default async function ProductPage({ params }: ProductPageProps) {
  const { id } = await params;
  const [device, product] = await Promise.all([getDevice(), readProduct(id)]);
  if (product.status !== 'ok') return <StatusEmptyState variant={product.status} size="page" />;
  return (
    <>
      <JsonLd data={buildProductPageJsonLd(product.data)} />
      {device === 'mobile' ? <ProductMobile product={product.data} /> : <ProductDesktop product={product.data} />}
    </>
  );
}

Every link to a product page, like every link to an indexable page, is the platform's NavLink, which shows a pending hint while the page loads, because the page has no loading.tsx to show at once (rendering-patterns.md).

The desktop template, a Server Component, renders the product at once and streams the two slower parts, each behind its own part boundary (error-handling.md):

<ProductSummary product={product} />
<PartBoundary name="related-products">
  <Suspense fallback={<RelatedProductsSkeleton />}>
    <RelatedProducts productId={product.id} />
  </Suspense>
</PartBoundary>
<PartBoundary name="product-reviews">
  <Suspense fallback={<ProductReviewsSkeleton />}>
    <ProductReviews productId={product.id} />
  </Suspense>
</PartBoundary>

.../product/[id]/organisms/related-products/RelatedProducts.tsx. The client only shows this part, so it stays a Server Component.

import { NavLink } from '@project/<platform>/app/navigation';
import { getRelatedProducts } from '@project/<platform>/server';
import { ProductRail } from '@project/island/organisms/product-rail';
import type { RelatedProductsProps } from './types';

export async function RelatedProducts({ productId }: RelatedProductsProps) {
  const products = await getRelatedProducts(productId);
  return <ProductRail products={products} linkAs={NavLink} />;
}

The rail renders each card's link with linkAs, the platform's NavLink, so a click is a client navigation and shows the pending hint while the product page loads (rendering-patterns.md).

.../product/[id]/organisms/product-reviews/ProductReviews.tsx. The client pages through reviews, so this part hands its first page over through query hydration. ReviewsList is a client component that calls the part model.

import { reviewKeys } from '@project/<platform>/features/catalog';
import { getProductReviews } from '@project/<platform>/server';
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { getQueryClient } from '../../../../../../configs';
import { ReviewsList } from './components/reviews-list';
import type { ProductReviewsProps } from './types';

export async function ProductReviews({ productId }: ProductReviewsProps) {
  const queryClient = getQueryClient();
  await queryClient.prefetchQuery({
    queryKey: reviewKeys.list(productId, 1),
    queryFn: () => getProductReviews(productId, 1),
  });
  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <ReviewsList productId={productId} />
    </HydrationBoundary>
  );
}

platforms/<platform>/src/features/catalog/models/product/use-product-reviews-part.ts. Page 1 comes from the server; later pages load in the browser while the current page stays visible.

import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { productsRepository, reviewKeys } from '../../repositories/products';

export function useProductReviewsPart(productId: string) {
  const [page, setPage] = useState(1);
  const reviews = useQuery({
    queryKey: reviewKeys.list(productId, page),
    queryFn: ({ signal }) => productsRepository.listReviews({ id: productId, page }, { signal }),
    placeholderData: keepPreviousData,
  });
  return { reviews, page, setPage };
}

apps/<app>/src/configs/react-query.ts. The app's root client component passes getQueryClient() to QueryClientProvider. Older TanStack Query v5 releases use the isServer constant instead of environmentManager.isServer(). The error settings are explained in error-handling.md.

import { handleError } from '@project/libs/error-handler';
import {
  defaultShouldDehydrateQuery,
  environmentManager,
  QueryCache,
  QueryClient,
} from '@tanstack/react-query';

function makeQueryClient(): QueryClient {
  return new QueryClient({
    queryCache: new QueryCache({
      onError: (error, query) => {
        if (query.state.data !== undefined) handleError(error, { where: 'refetch' });
      },
    }),
    defaultOptions: {
      queries: {
        staleTime: 60_000,
        retry: false,
        networkMode: 'offlineFirst',
        throwOnError: (_error, query) => query.state.data === undefined,
      },
      mutations: { networkMode: 'offlineFirst' },
      dehydrate: {
        shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending',
        shouldRedactErrors: () => false,
      },
    },
  });
}

let browserQueryClient: QueryClient | undefined;

export function getQueryClient(): QueryClient {
  if (environmentManager.isServer()) return makeQueryClient();
  browserQueryClient ??= makeQueryClient();
  return browserQueryClient;
}