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

6.9 KiB

Page example: caches, page, and parts

A full page for b2c-b2b.md: device detection, caches, a server page loader, the page entrypoint, 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.

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

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

export async function getDevice(): Promise<'mobile' | 'desktop'> {
  const { device } = userAgent({ headers: await headers() });
  return device.type === 'mobile' ? 'mobile' : 'desktop';
}

platforms/<app>/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/<app>/src/features/catalog/caches/server.ts

import 'server-only';

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

platforms/<app>/src/server.ts

import 'server-only';

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. generateMetadata and the page both call getProduct(id), and the cache sends one request. A page whose main read can answer 404 or 403 reads through readOnServer instead, as the order page in error-handling.md does.

import { getDevice, getProduct } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { ProductDesktop } from './templates/product-desktop';
import { ProductMobile } from './templates/product-mobile';

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

export async function generateMetadata({ params }: ProductPageProps): Promise<Metadata> {
  const { id } = await params;
  const product = await getProduct(id);
  return { title: product.name, description: product.summary };
}

export default async function ProductPage({ params }: ProductPageProps) {
  const { id } = await params;
  const [device, product] = await Promise.all([getDevice(), getProduct(id)]);
  return device === 'mobile' ? <ProductMobile product={product} /> : <ProductDesktop product={product} />;
}

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 { 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} />;
}

.../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/<app>/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;
}