Cursor rule for Next.js metadata with metadataBase, per-page generateMetadata, canonical URLs, Open Graph images, sitemap.ts, robots.ts and safely escaped JSON-LD.
.cursor/rules/next-js-metadata-and-seo.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for Next.js metadata with metadataBase, per-page generateMetadata, canonical URLs, Open Graph images, sitemap.ts, robots.ts and safely escaped JSON-LD."
globs: "**/*"
alwaysApply: false
---
# Next.js Metadata and SEO
Applies to: `metadata` / `generateMetadata` exports, metadata file conventions (`sitemap.ts`, `robots.ts`, `opengraph-image.tsx`) and structured data in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 metadata reference. Read `package.json` first; `params` is a Promise from Next.js 15 onward.
Metadata makes pages eligible for correct titles, previews and indexing; it does not guarantee rankings. Do not promise search results in code comments or copy.
## Root defaults
Set once in `app/layout.tsx`:
- `metadataBase` with the production origin, so relative URLs in `openGraph`, `twitter` and `alternates` resolve to absolute URLs.
- `title.template` (for example `'%s | Acme'`) plus `title.default`.
- A default `description` and `openGraph.siteName`.
## Per-page metadata
- Static pages export `metadata`. Dynamic pages export `generateMetadata`, await `params`, and return a unique `title`, `description` and `alternates.canonical`.
- Fetch the same record once for the page and its metadata: `fetch` is memoized automatically; wrap ORM calls in React `cache()`.
- Call `notFound()` in `generateMetadata` when the record does not exist so the page returns 404 rather than an empty title.
- Set `robots: { index: false }` for search results, drafts, account and checkout pages.
```tsx
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'
import { cache } from 'react'
import { notFound } from 'next/navigation'
import { db } from '@/lib/db'
const getPost = cache((slug: string) => db.post.findUnique({ where: { slug } }))
type Props = { params: Promise<{ slug: string }> }
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params
const post = await getPost(slug)
if (!post) notFound()
return {
title: post.title,
description: post.content.slice(0, 155),
alternates: { canonical: `/blog/${slug}` },
openGraph: { type: 'article', title: post.title, url: `/blog/${slug}` },
twitter: { card: 'summary_large_image', title: post.title },
}
}
export default async function Page({ params }: Props) {
const { slug } = await params
const post = await getPost(slug)
if (!post) notFound()
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: post.title,
dateModified: post.updatedAt.toISOString(),
}
return (
<article>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c') }}
/>
<h1>{post.title}</h1>
</article>
)
}
```
## Structured data
- Render JSON-LD in a `<script type="application/ld+json">` in the page and escape `<` as `<`; `JSON.stringify` alone does not prevent script injection from user content.
- Only describe what is visible on the page. Validate with the Rich Results Test or the Schema Markup Validator.
## Open Graph images
- Prefer `opengraph-image.tsx` (or a static `opengraph-image.png`) in the route folder. Generated images use `ImageResponse` from `next/og`, export `alt`, `size` and `contentType`, and receive `params` as a Promise.
- Use `twitter-image.*` or `twitter.images` only when the X/Twitter card needs a different image from Open Graph.
## Sitemap and robots
- `app/sitemap.ts` returns `MetadataRoute.Sitemap` with absolute URLs for indexable canonical pages only; use `generateSitemaps` when a single sitemap would be too large.
- `app/robots.ts` returns `MetadataRoute.Robots`, points to the sitemap and does not block assets needed to render pages.
```ts
// app/sitemap.ts
import type { MetadataRoute } from 'next'
import { db } from '@/lib/db'
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const posts = await db.post.findMany({ where: { published: true } })
return posts.map((post) => ({
url: `https://example.com/blog/${post.slug}`,
lastModified: post.updatedAt,
}))
}
```
## Verify before finishing
- `npx tsc --noEmit` passes.
- `curl -s http://localhost:3000/blog/<slug> | grep -E '<title>|rel="canonical"|og:image|application/ld\+json'` shows one title, one absolute canonical, the OG image and JSON-LD.
- A missing slug returns HTTP 404 (`curl -o /dev/null -w '%{http_code}'`).
- `/sitemap.xml` and `/robots.txt` load and list only canonical, indexable URLs.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
framework
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Adding metadata, canonical URLs, structured data and a sitemap to a blog in a Next.js 16 App Router project.
Blog posts live at app/blog/[slug]/page.tsx and are loaded with db.post.findUnique({ where: { slug } }). Add titles, descriptions, canonical URLs, Open Graph, BlogPosting JSON-LD and a sitemap for published posts. Production origin is https://example.com.Illustrative; not a recorded model run. Root layout sets metadataBase and a title template; the post page has generateMetadata awaiting params, sharing a cache()-wrapped getPost with the page, calling notFound() for missing posts and returning title, description, alternates.canonical, openGraph and twitter; the page renders JSON-LD with '<' escaped as \u003c; app/sitemap.ts returns absolute URLs for published posts; no claims about ranking improvements.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/next-js-metadata-and-seo.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Next.js Metadata and SEO: generateMetadata, Canonicals, OG Images and JSON-LD project conventions"
globs: "**/*"
alwaysApply: false
---
# Next.js Metadata and SEO
Applies to: `metadata` / `generateMetadata` exports, metadata file conventions (`sitemap.ts`, `robots.ts`, `opengraph-image.tsx`) and structured data in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 metadata reference. Read `package.json` first; `params` is a Promise from Next.js 15 onward.
Metadata makes pages eligible for correct titles, previews and indexing; it does not guarantee rankings. Do not promise search results in code comments or copy.
## Root defaults
Set once in `app/layout.tsx`:
- `metadataBase` with the production origin, so relative URLs in `openGraph`, `twitter` and `alternates` resolve to absolute URLs.
- `title.template` (for example `'%s | Acme'`) plus `title.default`.
- A default `description` and `openGraph.siteName`.
## Per-page metadata
- Static pages export `metadata`. Dynamic pages export `generateMetadata`, await `params`, and return a unique `title`, `description` and `alternates.canonical`.
- Fetch the same record once for the page and its metadata: `fetch` is memoized automatically; wrap ORM calls in React `cache()`.
- Call `notFound()` in `generateMetadata` when the record does not exist so the page returns 404 rather than an empty title.
- Set `robots: { index: false }` for search results, drafts, account and checkout pages.
```tsx
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'
import { cache } from 'react'
import { notFound } from 'next/navigation'
import { db } from '@/lib/db'
const getPost = cache((slug: string) => db.post.findUnique({ where: { slug } }))
type Props = { params: Promise<{ slug: string }> }
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params
const post = await getPost(slug)
if (!post) notFound()
return {
title: post.title,
description: post.content.slice(0, 155),
alternates: { canonical: `/blog/${slug}` },
openGraph: { type: 'article', title: post.title, url: `/blog/${slug}` },
twitter: { card: 'summary_large_image', title: post.title },
}
}
export default async function Page({ params }: Props) {
const { slug } = await params
const post = await getPost(slug)
if (!post) notFound()
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: post.title,
dateModified: post.updatedAt.toISOString(),
}
return (
<article>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c') }}
/>
<h1>{post.title}</h1>
</article>
)
}
```
## Structured data
- Render JSON-LD in a `<script type="application/ld+json">` in the page and escape `<` as `<`; `JSON.stringify` alone does not prevent script injection from user content.
- Only describe what is visible on the page. Validate with the Rich Results Test or the Schema Markup Validator.
## Open Graph images
- Prefer `opengraph-image.tsx` (or a static `opengraph-image.png`) in the route folder. Generated images use `ImageResponse` from `next/og`, export `alt`, `size` and `contentType`, and receive `params` as a Promise.
- Use `twitter-image.*` or `twitter.images` only when the X/Twitter card needs a different image from Open Graph.
## Sitemap and robots
- `app/sitemap.ts` returns `MetadataRoute.Sitemap` with absolute URLs for indexable canonical pages only; use `generateSitemaps` when a single sitemap would be too large.
- `app/robots.ts` returns `MetadataRoute.Robots`, points to the sitemap and does not block assets needed to render pages.
```ts
// app/sitemap.ts
import type { MetadataRoute } from 'next'
import { db } from '@/lib/db'
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const posts = await db.post.findMany({ where: { published: true } })
return posts.map((post) => ({
url: `https://example.com/blog/${post.slug}`,
lastModified: post.updatedAt,
}))
}
```
## Verify before finishing
- `npx tsc --noEmit` passes.
- `curl -s http://localhost:3000/blog/<slug> | grep -E '<title>|rel="canonical"|og:image|application/ld\+json'` shows one title, one absolute canonical, the OG image and JSON-LD.
- A missing slug returns HTTP 404 (`curl -o /dev/null -w '%{http_code}'`).
- `/sitemap.xml` and `/robots.txt` load and list only canonical, indexable URLs.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.