diff --git a/README.md b/README.md index e215bc4..8091764 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,28 @@ You can start editing the page by modifying `app/page.tsx`. The page auto-update This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. +## CMS SEO and Publish Cache + +CMS routes read custom SEO title/description (falling back to standard Wagtail +SEO fields), canonical URL, social image, and JSON-LD. Explicit CMS SEO titles +are output without appending the site title template. Empty JSON-LD is omitted, +and script boundaries are escaped before output. + +Deploy the backend API changes first, then build and restart the frontend. +No database migrations are required. Set `NEXT_PUBLIC_API_URL` to the public +CMS origin before building the frontend. + +Set backend `FRONTEND_REVALIDATE_URL` to the frontend `/api/revalidate` endpoint. +Both services must use the same `REVALIDATE_SECRET`. All Wagtail page requests +share the `wagtail-pages` tag. Publishing expires this tag immediately, and the +next request fetches fresh data. This refreshes all page caches, including lists. +Snippet caches retain separate tags. Without a working webhook, the existing +60-second time-based revalidation remains the fallback. + +Frontend tests: `node --test tests/seo.test.cjs`. +Backend tests (from the backend root): +`python -m pytest apps/core/tests.py -k "page_api_exposes_seo_fields or seo_image_serializer or notify_frontend_revalidate"`. + ## Learn More To learn more about Next.js, take a look at the following resources: diff --git a/app/api/revalidate/route.ts b/app/api/revalidate/route.ts index 6416aec..598e9b0 100644 --- a/app/api/revalidate/route.ts +++ b/app/api/revalidate/route.ts @@ -26,8 +26,7 @@ export async function POST(request: NextRequest) { } for (const tag of tags) { - // Next.js 16 要求传入 cache profile;"max" 表示立即使该标签下的缓存完全失效。 - revalidateTag(tag, "max"); + revalidateTag(tag, { expire: 0 }); } return NextResponse.json({ revalidated: tags }); diff --git a/app/blog/[slug]/page.tsx b/app/blog/[slug]/page.tsx index 4783411..dcd6054 100644 --- a/app/blog/[slug]/page.tsx +++ b/app/blog/[slug]/page.tsx @@ -4,6 +4,8 @@ import { getBlogBySlug } from "@/services/blog.service"; import { getPreviewOrFallback } from "@/services/preview.service"; import { BlockRenderer } from "@/blocks/BlockRenderer"; import type { BlogPageDetail } from "@/types/wagtail"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; interface BlogDetailPageProps { params: Promise<{ slug: string }>; @@ -13,8 +15,7 @@ export async function generateMetadata({ params, }: BlogDetailPageProps): Promise { const { slug } = await params; - const post = await getBlogBySlug(slug).catch(() => null); - return { title: post?.title ?? "文章未找到" }; + return createPageMetadata(await getPageSEO("blog.BlogPage", slug).catch(() => null), "文章未找到"); } export default async function BlogDetailPage({ params }: BlogDetailPageProps) { @@ -31,6 +32,7 @@ export default async function BlogDetailPage({ params }: BlogDetailPageProps) { return (
+

{post.title}

{post.published_at && (

{post.published_at}

diff --git a/app/blog/page.tsx b/app/blog/page.tsx index 8ce23e8..cbc06ef 100644 --- a/app/blog/page.tsx +++ b/app/blog/page.tsx @@ -1,16 +1,19 @@ import Link from "next/link"; import type { Metadata } from "next"; import { getBlogList } from "@/services/blog.service"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; -export const metadata: Metadata = { - title: "技术博客", -}; +export async function generateMetadata(): Promise { + return createPageMetadata(await getPageSEO("blog.BlogIndexPage", "blog").catch(() => null), "技术博客"); +} export default async function BlogListPage() { const posts = await getBlogList().catch(() => []); return (
+

技术博客

    {posts.map((post) => ( diff --git a/app/cases/[slug]/page.tsx b/app/cases/[slug]/page.tsx index a9c2104..b5a8219 100644 --- a/app/cases/[slug]/page.tsx +++ b/app/cases/[slug]/page.tsx @@ -4,6 +4,8 @@ import { getCaseStudyBySlug } from "@/services/case.service"; import { getPreviewOrFallback } from "@/services/preview.service"; import { BlockRenderer } from "@/blocks/BlockRenderer"; import type { CaseStudyPageDetail } from "@/types/wagtail"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; interface CaseStudyDetailPageProps { params: Promise<{ slug: string }>; @@ -13,8 +15,7 @@ export async function generateMetadata({ params, }: CaseStudyDetailPageProps): Promise { const { slug } = await params; - const item = await getCaseStudyBySlug(slug).catch(() => null); - return { title: item?.title ?? "案例未找到" }; + return createPageMetadata(await getPageSEO("cases.CaseStudyPage", slug).catch(() => null), "案例未找到"); } export default async function CaseStudyDetailPage({ @@ -33,6 +34,7 @@ export default async function CaseStudyDetailPage({ return (
    +

    {item.title}

    {item.client_name} diff --git a/app/cases/page.tsx b/app/cases/page.tsx index 5013815..0a24ebf 100644 --- a/app/cases/page.tsx +++ b/app/cases/page.tsx @@ -1,16 +1,19 @@ import Link from "next/link"; import type { Metadata } from "next"; import { getCaseStudyList } from "@/services/case.service"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; -export const metadata: Metadata = { - title: "客户案例", -}; +export async function generateMetadata(): Promise { + return createPageMetadata(await getPageSEO("cases.CaseStudyIndexPage", "cases").catch(() => null), "客户案例"); +} export default async function CaseStudyListPage() { const caseStudies = await getCaseStudyList().catch(() => []); return (

    +

    客户案例

      {caseStudies.map((item) => ( diff --git a/app/contact/page.tsx b/app/contact/page.tsx index 8d8aa2b..05c546e 100644 --- a/app/contact/page.tsx +++ b/app/contact/page.tsx @@ -3,13 +3,11 @@ import { getContactPage } from "@/services/page.service"; import { getPreviewOrFallback } from "@/services/preview.service"; import { BlockRenderer } from "@/blocks/BlockRenderer"; import type { ContactPageDetail } from "@/types/wagtail"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; export async function generateMetadata(): Promise { - const page = await getContactPage().catch(() => null); - return { - title: page?.seo_title_override || page?.title || "联系我们", - description: page?.seo_description_override, - }; + return createPageMetadata(await getPageSEO("core.ContactPage", "contact").catch(() => null), "联系我们"); } export default async function ContactPage() { @@ -36,5 +34,5 @@ export default async function ContactPage() { ); } - return ; + return <>; } diff --git a/app/page.tsx b/app/page.tsx index 0a61b33..fdbc1c1 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -3,10 +3,12 @@ import { getHomePage } from "@/services/page.service"; import { getPreviewOrFallback } from "@/services/preview.service"; import { BlockRenderer } from "@/blocks/BlockRenderer"; import type { HomePageDetail } from "@/types/wagtail"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; -export const metadata: Metadata = { - title: "首页", -}; +export async function generateMetadata(): Promise { + return createPageMetadata(await getPageSEO("home.HomePage").catch(() => null), "首页"); +} export default async function Home() { const homePage = await getPreviewOrFallback( @@ -33,5 +35,5 @@ export default async function Home() { ); } - return ; + return <>; } diff --git a/app/privacy-policy/page.tsx b/app/privacy-policy/page.tsx index 459b602..1fd130a 100644 --- a/app/privacy-policy/page.tsx +++ b/app/privacy-policy/page.tsx @@ -1,10 +1,11 @@ import { notFound } from "next/navigation"; import type { Metadata } from "next"; import { getSimpleContentPageBySlug } from "@/services/legal.service"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; export async function generateMetadata(): Promise { - const page = await getSimpleContentPageBySlug("privacy-policy").catch(() => null); - return { title: page?.title ?? "隐私政策" }; + return createPageMetadata(await getPageSEO("core.SimpleContentPage", "privacy-policy").catch(() => null), "隐私政策"); } export default async function PrivacyPolicyPage() { @@ -16,6 +17,7 @@ export default async function PrivacyPolicyPage() { return (
      +

      {page.title}

      {/* page.body 为 Wagtail RichTextField 渲染出的 HTML,内容仅由后台编辑人员维护,非用户输入,可信任直接渲染 */}
      ; @@ -13,8 +15,7 @@ export async function generateMetadata({ params, }: ProductDetailPageProps): Promise { const { slug } = await params; - const product = await getProductBySlug(slug).catch(() => null); - return { title: product?.title ?? "产品未找到" }; + return createPageMetadata(await getPageSEO("products.ProductPage", slug).catch(() => null), "产品未找到"); } export default async function ProductDetailPage({ @@ -33,6 +34,7 @@ export default async function ProductDetailPage({ return (
      +

      {product.title}

      diff --git a/app/products/page.tsx b/app/products/page.tsx index 78ead88..6dc136f 100644 --- a/app/products/page.tsx +++ b/app/products/page.tsx @@ -1,16 +1,19 @@ import Link from "next/link"; import type { Metadata } from "next"; import { getProductList } from "@/services/product.service"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; -export const metadata: Metadata = { - title: "产品", -}; +export async function generateMetadata(): Promise { + return createPageMetadata(await getPageSEO("products.ProductIndexPage", "products").catch(() => null), "产品"); +} export default async function ProductListPage() { const products = await getProductList().catch(() => []); return (
      +

      产品

        {products.map((product) => ( diff --git a/app/solutions/[slug]/page.tsx b/app/solutions/[slug]/page.tsx index d38f22a..b472558 100644 --- a/app/solutions/[slug]/page.tsx +++ b/app/solutions/[slug]/page.tsx @@ -4,6 +4,8 @@ import { getSolutionBySlug } from "@/services/solution.service"; import { getPreviewOrFallback } from "@/services/preview.service"; import { BlockRenderer } from "@/blocks/BlockRenderer"; import type { SolutionPageDetail } from "@/types/wagtail"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; interface SolutionDetailPageProps { params: Promise<{ slug: string }>; @@ -13,8 +15,7 @@ export async function generateMetadata({ params, }: SolutionDetailPageProps): Promise { const { slug } = await params; - const solution = await getSolutionBySlug(slug).catch(() => null); - return { title: solution?.title ?? "解决方案未找到" }; + return createPageMetadata(await getPageSEO("solutions.SolutionPage", slug).catch(() => null), "解决方案未找到"); } export default async function SolutionDetailPage({ @@ -33,6 +34,7 @@ export default async function SolutionDetailPage({ return (
        +

        {solution.title}

        diff --git a/app/solutions/page.tsx b/app/solutions/page.tsx index c8d33f5..1d133c9 100644 --- a/app/solutions/page.tsx +++ b/app/solutions/page.tsx @@ -1,16 +1,19 @@ import Link from "next/link"; import type { Metadata } from "next"; import { getSolutionList } from "@/services/solution.service"; +import { createPageMetadata, getPageSEO } from "@/services/seo.service"; +import PageSEO from "@/components/layout/PageSEO"; -export const metadata: Metadata = { - title: "解决方案", -}; +export async function generateMetadata(): Promise { + return createPageMetadata(await getPageSEO("solutions.SolutionIndexPage", "solutions").catch(() => null), "解决方案"); +} export default async function SolutionListPage() { const solutions = await getSolutionList().catch(() => []); return (
        +

        解决方案

          {solutions.map((solution) => ( diff --git a/components/layout/PageSEO.tsx b/components/layout/PageSEO.tsx new file mode 100644 index 0000000..09f9525 --- /dev/null +++ b/components/layout/PageSEO.tsx @@ -0,0 +1,14 @@ +import { getPageSEO } from "@/services/seo.service"; + +export default async function PageSEO({ type, slug }: { type: string; slug?: string }) { + const page = await getPageSEO(type, slug).catch(() => null); + if (!page?.schema_json || Object.keys(page.schema_json).length === 0) return null; + return ( + " }; + const { default: PageSEO } = loadModule("components/layout/PageSEO.tsx", { + "@/services/seo.service": { getPageSEO: async () => ({ schema_json: schema }) }, + }); + const element = await PageSEO({ type: "home.HomePage" }); + const json = element.props.dangerouslySetInnerHTML.__html; + assert.ok(!json.includes("<")); + assert.deepEqual(JSON.parse(json), schema); + const empty = loadModule("components/layout/PageSEO.tsx", { + "@/services/seo.service": { getPageSEO: async () => ({ schema_json: {} }) }, + }); + assert.equal(await empty.default({ type: "home.HomePage" }), null); +}); + +test("page fetches share the publish cache tag without changing snippet tags", async () => { + const calls = []; + const { fetchAPI } = loadModule("services/api-client.ts", {}, { + fetch: async (url, options) => { calls.push(options); return { ok: true, json: async () => ({}) }; }, + }); + await fetchAPI("/api/v2/pages/?type=home.HomePage", { tags: ["home-page", "wagtail-pages"] }); + assert.equal(calls[0].next.tags.join(","), "wagtail-pages,home-page"); + await fetchAPI("/api/v1/custom/core/site-settings/", { tags: ["site-settings"] }); + assert.equal(calls[1].next.tags.join(","), "site-settings"); +}); + +test("authenticated webhook expires shared cache immediately and rejects unauthorized requests", async () => { + const calls = []; + const { POST } = loadModule("app/api/revalidate/route.ts", { + "next/cache": { revalidateTag: (tag, profile) => calls.push({ tag, profile }) }, + }, { process: { env: { REVALIDATE_SECRET: "test-secret" } } }); + const request = (authorization) => ({ + headers: { get: () => authorization }, + json: async () => ({ tags: ["wagtail-pages"] }), + }); + assert.equal((await POST(request("Bearer test-secret"))).status, 200); + assert.equal(calls[0].tag, "wagtail-pages"); + assert.equal(calls[0].profile.expire, 0); + assert.equal((await POST(request("Bearer invalid"))).status, 401); + assert.equal(calls.length, 1); +}); + +test("all CMS page routes wire metadata and JSON-LD to the correct page model", async () => { + const routes = [ + ["app/page.tsx", "home.HomePage", undefined], + ["app/products/page.tsx", "products.ProductIndexPage", "products"], + ["app/solutions/page.tsx", "solutions.SolutionIndexPage", "solutions"], + ["app/cases/page.tsx", "cases.CaseStudyIndexPage", "cases"], + ["app/blog/page.tsx", "blog.BlogIndexPage", "blog"], + ["app/contact/page.tsx", "core.ContactPage", "contact"], + ["app/privacy-policy/page.tsx", "core.SimpleContentPage", "privacy-policy"], + ["app/products/[slug]/page.tsx", "products.ProductPage", "test-slug"], + ["app/solutions/[slug]/page.tsx", "solutions.SolutionPage", "test-slug"], + ["app/cases/[slug]/page.tsx", "cases.CaseStudyPage", "test-slug"], + ["app/blog/[slug]/page.tsx", "blog.BlogPage", "test-slug"], + ]; + const { createPageMetadata } = loadModule("services/seo.service.ts", { "./api-client": {} }); + const PageSEO = () => null; + const service = { + getHomePage: async () => page, getContactPage: async () => page, + getProductList: async () => [], getSolutionList: async () => [], + getCaseStudyList: async () => [], getBlogList: async () => [], + getProductBySlug: async () => page, getSolutionBySlug: async () => page, + getCaseStudyBySlug: async () => page, getBlogBySlug: async () => page, + getSimpleContentPageBySlug: async () => page, + }; + const mocks = { + "@/components/layout/PageSEO": { default: PageSEO }, + "@/blocks/BlockRenderer": { BlockRenderer: () => null }, + "@/services/preview.service": { getPreviewOrFallback: async (type, fields, fallback) => fallback() }, + }; + for (const name of ["page", "product", "solution", "case", "blog", "legal"]) { + mocks[`@/services/${name}.service`] = service; + } + function findSEO(element) { + if (!element || typeof element !== "object") return null; + if (element.type === PageSEO) return element; + const children = element.props?.children; + for (const child of Array.isArray(children) ? children : [children]) { + const found = findSEO(child); + if (found) return found; + } + return null; + } + for (const [file, expectedType, expectedSlug] of routes) { + const calls = []; + const route = loadModule(file, { + ...mocks, + "@/services/seo.service": { + createPageMetadata, + getPageSEO: async (type, slug) => { calls.push({ type, slug }); return page; }, + }, + }); + const props = { params: Promise.resolve({ slug: "test-slug" }) }; + assert.equal((await route.generateMetadata(props)).title.absolute, page.seo_title_override, file); + assert.equal(calls[0].type, expectedType, file); + assert.equal(calls[0].slug, expectedSlug, file); + const element = findSEO(await route.default(props)); + assert.ok(element, file); + assert.equal(element.props.type, expectedType, file); + assert.equal(element.props.slug, expectedSlug, file); + } +}); \ No newline at end of file diff --git a/types/wagtail.ts b/types/wagtail.ts index 117cd8c..fc12b40 100644 --- a/types/wagtail.ts +++ b/types/wagtail.ts @@ -10,12 +10,19 @@ export interface WagtailMeta { html_url: string | null; slug: string; first_published_at: string | null; + seo_title?: string; + search_description?: string; } export interface WagtailPageSummary { id: number; meta: WagtailMeta; title: string; + seo_title_override?: string; + seo_description_override?: string; + og_image?: { url: string; title: string } | null; + canonical_url?: string; + schema_json?: Record; } export interface WagtailListResponse {