# Page example: caches, page, and parts A full page for [b2c-b2b.md](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//src/shared/utils/get-device.ts` ```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//src/features/catalog/caches/products.ts` ```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//src/features/catalog/caches/server.ts` ```ts import 'server-only'; export { getProduct, getProductReviews, getRelatedProducts } from './products'; ``` `platforms//src/server.ts` ```ts import 'server-only'; export { getProduct, getProductReviews, getRelatedProducts } from './features/catalog/caches/server'; export { getDevice } from './shared/utils/get-device'; ``` `apps//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](error-handling-code.md) does. ```tsx import { getDevice, getProduct } from '@project//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 { 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' ? : ; } ``` 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](error-handling.md#boundaries)): ```tsx }> }> ``` `.../product/[id]/organisms/related-products/RelatedProducts.tsx`. The client only shows this part, so it stays a Server Component. ```tsx import { getRelatedProducts } from '@project//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 ; } ``` `.../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. ```tsx import { reviewKeys } from '@project//features/catalog'; import { getProductReviews } from '@project//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 ( ); } ``` `platforms//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. ```ts 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//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](error-handling.md#reads). ```ts 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; } ```