Строгая схема публичного Next.js frontend: App Router, маршруты, серверные запросы к Payload, кэширование, revalidation, pagination, metadata, sitemap, preview, loading/error states и правила безопасной работы с CMS.
После Build 04 должен существовать рабочий skeleton публичного сайта, который получает данные из Payload, правильно обрабатывает маршруты и может масштабироваться до 100 000 статей без загрузки каталога в браузер.
src/app/ ├── (payload)/ │ └── ... Payload admin/API routes ├── (frontend)/ │ ├── layout.tsx │ ├── page.tsx │ ├── article/ │ │ └── [slug]/ │ │ ├── page.tsx │ │ ├── loading.tsx │ │ └── error.tsx │ ├── category/ │ │ └── [slug]/ │ │ └── page.tsx │ ├── topic/ │ │ └── [slug]/ │ │ └── page.tsx │ ├── terms/ │ │ └── page.tsx │ ├── term/ │ │ └── [slug]/ │ │ └── page.tsx │ ├── search/ │ │ └── page.tsx │ └── preview/ │ └── route.ts ├── sitemap.ts ├── robots.ts ├── not-found.tsx └── globals.css
| Route | Назначение | Источник | Рендеринг |
|---|---|---|---|
| / | Главная | Articles + Categories + Globals | Server Component |
| /article/[slug] | Статья | Article + relationships | Server Component |
| /category/[slug] | Рубрика | Category + paginated Articles | Server Component |
| /topic/[slug] | Тематический кластер | Topic + paginated Articles | Server Component |
| /terms | Глоссарий | Terms | Server Component |
| /term/[slug] | Термин | Term + related Articles | Server Component |
| /search?q=... | Поиск | Meilisearch adapter | Server + client search form |
Route / Server Component
↓
lib/payload/queries.ts
↓
Payload Local API
↓
PostgreSQL
Result
↓
transform/view model
↓
presentation componentimport { getPayload } from 'payload'
import config from '@payload-config'
export async function getPayloadClient() {
return getPayload({ config })
}export async function getArticleBySlug(slug: string, draft = false) {
const payload = await getPayloadClient()
const result = await payload.find({
collection: 'articles',
where: {
slug: { equals: slug },
...(!draft ? {
_status: { equals: 'published' }
} : {}),
},
limit: 1,
depth: 2,
draft,
})
return result.docs[0] ?? null
}export default async function ArticlePage({ params }) {
const { slug } = await params
const article = await getArticleBySlug(slug)
if (!article) notFound()
return <ArticlePageView article={toArticlePageView(article)} />
}notFound()./category/wood?page=1
/category/wood?page=2
const page = Math.max(1, Number(searchParams.page ?? 1))
const limit = 24
payload.find({
collection: 'articles',
where: {
category: { equals: category.id },
_status: { equals: 'published' },
},
sort: '-publishedAt',
page,
limit,
})| Компонент | Тип | Причина |
|---|---|---|
| Page route | Server | data fetching / SEO |
| ArticleCard | Server по умолчанию | нет интерактива |
| ArticleBody | Server | контент |
| TOC | Server + маленький client helper при необходимости | sticky/active heading |
| Search form | Client допустим | интерактив |
| Mobile menu | Client | UI state |
| Gallery controls | Client | интерактив |
Не применять один режим ко всему сайту. Кэшировать по типу данных.
| Контент | Рекомендация |
|---|---|
| Article published | кэш + invalidation после publish/update |
| Category/Topic listings | revalidate / tag invalidation |
| Globals | длинный cache + invalidation after change |
| Search | динамический запрос |
| Draft preview | no-store / dynamic |
| Recommendations personalized | динамически или короткий cache |
Payload publish/update
↓
afterChange hook
↓
invalidate:
- article:{slug}
- category:{categorySlug}
- relevant topic tags
- home feed tag
↓
Next.js serves fresh contentarticle:{articleId}
article-slug:{slug}
category:{categoryId}
topic:{topicId}
term:{termId}
home
navigation
site-settingsРеализация зависит от фактической версии Next.js. Кодер должен использовать актуальный поддерживаемый механизм invalidation для установленной версии.
Payload Admin ↓ preview URL /frontend/preview?...signed token... ↓ validate token/user ↓ enable draft mode ↓ redirect /article/[slug] ↓ server fetch with draft=true
loading.tsx использовать только там, где streaming действительно улучшает UX.
not-found.tsx — отсутствующий slug/document.error.tsx — runtime ошибки route segment.| Сервис недоступен | Поведение сайта |
|---|---|
| Payload/PostgreSQL | core content недоступен → controlled error |
| Meilisearch | search unavailable / fallback message |
| Gorse | скрыть персональные рекомендации, можно показать editorial related |
| Ads | пустой slot, layout не ломается |
| Analytics | страница работает без analytics |
export async function generateMetadata({ params }) {
const { slug } = await params
const article = await getArticleMetaBySlug(slug)
if (!article) return {}
return {
title: article.metaTitle ?? article.title,
description: article.metaDescription ?? article.excerpt,
alternates: {
canonical: article.canonicalUrl ?? `/article/${article.slug}`,
},
openGraph: {
title: article.metaTitle ?? article.title,
description: article.metaDescription ?? article.excerpt,
images: article.ogImage ? [article.ogImage.url] : [],
},
}
}contentBlocks.allow: / disallow: /admin /api /preview /search?* // в зависимости от выбранной SEO-политики sitemap: https://DOMAIN/sitemap.xml
updatedAt как lastModified там, где корректно./sitemap.xml ↓ sitemap index ├── /sitemaps/articles-1.xml ├── /sitemaps/articles-2.xml ├── /sitemaps/articles-3.xml ├── /sitemaps/categories.xml ├── /sitemaps/topics.xml └── /sitemaps/terms.xml
/search?q=router&page=1 1. sanitize q 2. min query length 3. request Meilisearch 4. get ids / indexed card fields 5. render result cards 6. pagination 7. noindex
| Query | Что НЕ нужно загружать |
|---|---|
| ArticleCard list | contentBlocks, full related docs, heavy source metadata |
| Navigation | articles |
| Metadata | contentBlocks |
| Terms list | full term body |
| Sitemap | images, body, relationships beyond slug/date |
depth по умолчанию.HomePageView ArticlePageView CategoryPageView TopicPageView TermsIndexView TermPageView SearchPageView
Route получает CMS data → transform → page view model. Presentation components не должны напрямую работать с необработанными Payload documents.
NEXT_PUBLIC_* значения.Promise.all([ getSiteSettings(), getNavigation(), getFeaturedArticle(), getActiveCategories(), getLatestArticles(), getHomeCategorySections(), getTermsTeaser(), ]) ↓ transforms ↓ HomePageView
Если инфраструктура не предоставляет БД во время build, выбрать документированную стратегию: dynamic routes либо поддерживаемый режим compile/generate. Решение записать в deployment report.
| # | Тест | PASS |
|---|---|---|
| R01 | / | 200 + Payload content |
| R02 | published article | 200 |
| R03 | draft article anonymous | 404/deny |
| R04 | unknown article slug | 404 |
| R05 | category page 1 | 200 + 24 max |
| R06 | category page 2 | different records |
| R07 | unknown category | 404 |
| R08 | term route | 200 |
| R09 | search empty query | controlled state |
| R10 | search service down | site remains operational |
| # | Проверка | PASS |
|---|---|---|
| S01 | Article title | metadata generated |
| S02 | Canonical | correct public URL |
| S03 | Old slug | 301 redirect |
| S04 | Sitemap | only published/indexable |
| S05 | Robots | admin/api/preview protected |
| S06 | Search | noindex policy applied |
force-dynamic на весь сайт «чтобы просто работало» без измеренной причины.1. app route tree 2. lib/payload/client.ts 3. lib/payload/queries.ts 4. lib/payload/transforms.ts 5. metadata implementation 6. sitemap implementation 7. robots implementation 8. preview implementation 9. cache/invalidation implementation 10. pagination implementation 11. route test report 12. SEO test report 13. cache test report 14. build report 15. deviations.md 16. commit hash
build_05_article_page.html — полная длинная article page в стиле Fyrre: layout, typography, TOC, structured blocks, изображения, таблицы, warning-блоки, glossary links, sources, related content, ads и mobile behavior.