Skip to content

Commit cb3092c

Browse files
feat(llm): Follow Vercel's Markdown and agent discovery guidance (#20930)
## DESCRIBE YOUR PR Brings docs.sentry.io in line with Vercel's [Markdown and Agent Discovery](https://vercel.com/docs/agent-resources/markdown-access) guidance and the [llms.txt v2](https://llmstxt.org/) link relations. We already had the `.md` exports, content negotiation, `llms.txt`, and the **View as Markdown** button. This PR adds the parts that were missing. **Content negotiation honors quality values.** The middleware used to serve Markdown whenever `Accept` contained `text/markdown`, and to any recognized AI user-agent regardless of `Accept`. Now (`src/lib/contentNegotiation.ts`): - Markdown is served when `Accept` ranks `text/markdown` at or above `text/html`. A tie goes to Markdown, so `text/markdown, text/html, */*` (Claude Code's WebFetch) still gets Markdown, but `text/html, text/markdown;q=0.9` now gets HTML. - A recognized AI agent whose `Accept` names neither format (`*/*`, empty) gets Markdown. One that explicitly asks for `text/html` gets HTML. **Markdown responses** (negotiated or `.md`) set `Vary: Accept` and a `Link` header with `rel="canonical"` (the HTML page) and `rel="describedby"` (`/llms.txt`). Before, the canonical link was only on `.md` URLs. **HTML pages** advertise their Markdown version two ways: a `Link` response header (`rel="alternate"; type="text/markdown"` plus `rel="describedby"`), and the same links as `<link>` tags in `<head>`. The header lets agents that run `curl -I` find the Markdown without parsing HTML. **Discovery index.** `scripts/generate-llms-txt.mjs` now also writes `/sitemap.md`: every visible page, nested like the sidebar, with its description and `.md` URL (~340 KB, ~2,000 pages; Vercel's is ~540 KB). Every page export ends with a footer linking `/sitemap.md` and `/llms.txt`, and `llms.txt` and the Markdown soft-404 link the sitemap. `specs/llm-friendly-docs.md` and `AGENTS.md` are updated to match. ### Notes for review - **Behavior change for agents that send browser-style `Accept` headers.** An agent matching `AI_AGENT_PATTERN` that sends `text/html,...,*/*;q=0.8` now gets HTML, not Markdown. This is what Vercel's guidance asks for ("A recognized AI agent receives HTML when it requests `text/html`"). Before merging, check `docs.request.classified` / the `Middleware request processed` logs for which agents send `text/html` without `text/markdown`, to see how much traffic moves to HTML. If that's too much, `shouldServeMarkdown` can keep the user-agent override for agents. - **No `Vary: Accept` on HTML responses.** The App Router page renderer calls `res.setHeader('Vary', …)`, which replaces any `Vary` the middleware sets, so a middleware `Vary` on HTML is dropped (confirmed on `next dev`). Markdown responses keep `Vary: Accept`, which stops caches from serving Markdown to browsers. Vercel's own docs set `Vary: Accept` only on Markdown responses too. - **The footer changes every export once**, so the first build after merge re-uploads every file to R2 and logs the ">10% different hash" warning. - **Left out on purpose:** the Vercel-specific parts (`graph.json` / `.graph.md` cross-link maps, the `vercel docs` CLI, `.well-known/ai-catalog.json`), the extra frontmatter fields (`last_updated`, `type`, `prerequisites`, `related`) that we don't have data for, and `llms-full.txt`. ## IS YOUR CHANGE URGENT? - [ ] Urgent deadline (GA date, etc.): YYYY-MM-DD - [ ] Other deadline: YYYY-MM-DD - [x] No deadline: Not urgent, can wait up to 1 week+ ## PRE-MERGE CHECKLIST - [ ] Checked Vercel preview for correctness, including links - [ ] PR was reviewed and approved by any necessary SMEs (subject matter experts) - [ ] PR was reviewed and approved by a member of the [Sentry docs team](https://github.com/orgs/getsentry/teams/docs) <!-- junior-request-attribution:start --> via @sergical. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:slack%3AC0CDFPETHS4%3A1795221617.574909 --> -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AC0CDFPETHS4%3A1795221617.574909) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0CDFPETHS4%3A1795221617.574909/?project=4510944073809921) <!-- junior-session-footer:end --> --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Sergiy Dybskiy <3760543+sergical@users.noreply.github.com>
1 parent 805e055 commit cb3092c

13 files changed

Lines changed: 327 additions & 81 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ When writing requirements in `develop-docs/`:
114114
- Auto-generated from `public/doctree.json` by `scripts/generate-llms-txt.mjs`
115115
- Run `pnpm generate-llms-txt` to regenerate, or it runs automatically as part of `pnpm build`
116116
- Includes: product description, AI agent instructions, platform/section index, links to agent skills at `skills.sentry.dev`
117+
- The same script generates `/sitemap.md`, which lists every page with its description
117118

118119
## Sentry Product Skills (sentry-for-ai)
119120

‎app/[[...path]]/page.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {Metadata} from 'next';
33
import {notFound} from 'next/navigation';
44
import {Fragment, useMemo} from 'react';
55
import {apiCategories} from 'sentry-docs/build/resolveOpenAPI';
6-
import {resolvePageCanonical} from 'sentry-docs/canonical';
6+
import {markdownExportPath, resolvePageCanonical} from 'sentry-docs/canonical';
77
import {ApiCategoryPage} from 'sentry-docs/components/apiCategoryPage';
88
import {ApiPage} from 'sentry-docs/components/apiPage';
99
import {DocPage} from 'sentry-docs/components/docPage';
@@ -414,6 +414,10 @@ export async function generateMetadata(props: MetadataProps): Promise<Metadata>
414414
},
415415
alternates: {
416416
canonical,
417+
// Points agents at the page's Markdown export (llmstxt.org link relation).
418+
types: {
419+
'text/markdown': `${DOCS_ORIGIN}${markdownExportPath(params.path?.join('/') ?? '')}`,
420+
},
417421
},
418422
robots: noindex ? 'noindex' : undefined,
419423
};

‎app/layout.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ export default function RootLayout({children}: {children: React.ReactNode}) {
3434
return (
3535
<html lang="en" suppressHydrationWarning>
3636
<head>
37+
{/* llms.txt covers every page on the site (llmstxt.org link relation). */}
38+
<link rel="describedby" type="text/plain" href="/llms.txt" />
3739
<PlausibleProvider taggedEvents domain="docs.sentry.io,rollup.sentry.io" />
3840
</head>
3941
<body className={rubik.variable} suppressHydrationWarning>

‎app/md-exports/[...path]/route.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ function findWhatYouNeedLines(): string[] {
7777
'## Find what you need',
7878
'',
7979
`- [Site index](${DOCS_ORIGIN}/llms.txt) — LLM-optimized page listing`,
80+
`- [Sitemap](${DOCS_ORIGIN}/sitemap.md) — every page with a one-line summary`,
8081
`- [Documentation root](${DOCS_ORIGIN}/index.md) — full docs overview`,
8182
`- [Platforms](${DOCS_ORIGIN}/platforms.md) — all SDK platforms`,
8283
'',

‎middleware.test.ts‎

Lines changed: 77 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ describe('canonical Link header on .md responses', () => {
246246
it('adds Link rel=canonical pointing to the HTML page for a deep path', async () => {
247247
const {middleware} = await importMiddleware({});
248248
const res = middleware(makeRequest('/platforms/apple/cocoa.md'));
249-
expect(res.headers.get('Link')).toBe(
249+
expect(res.headers.get('Link')).toContain(
250250
'<https://docs.sentry.io/platforms/apple/cocoa/>; rel="canonical"'
251251
);
252252
});
@@ -257,37 +257,66 @@ describe('canonical Link header on .md responses', () => {
257257
])('does not add a trailing slash to a dotted document path: %s', async path => {
258258
const {middleware} = await importMiddleware({});
259259
const res = middleware(makeRequest(`${path}.md`));
260-
expect(res.headers.get('Link')).toBe(
260+
expect(res.headers.get('Link')).toContain(
261261
`<https://docs.sentry.io${path}>; rel="canonical"`
262262
);
263263
});
264264

265265
it('maps /index.md to the root canonical URL', async () => {
266266
const {middleware} = await importMiddleware({});
267267
const res = middleware(makeRequest('/index.md'));
268-
expect(res.headers.get('Link')).toBe('<https://docs.sentry.io/>; rel="canonical"');
268+
expect(res.headers.get('Link')).toContain(
269+
'<https://docs.sentry.io/>; rel="canonical"'
270+
);
269271
});
270272

271273
it('handles top-level .md paths', async () => {
272274
const {middleware} = await importMiddleware({});
273275
const res = middleware(makeRequest('/platforms.md'));
274-
expect(res.headers.get('Link')).toBe(
276+
expect(res.headers.get('Link')).toContain(
275277
'<https://docs.sentry.io/platforms/>; rel="canonical"'
276278
);
277279
});
278280

279281
it('uses develop.sentry.dev origin in developer docs mode', async () => {
280282
const {middleware} = await importMiddleware({NEXT_PUBLIC_DEVELOPER_DOCS: '1'});
281283
const res = middleware(makeRequest('/platforms/apple/cocoa.md'));
282-
expect(res.headers.get('Link')).toBe(
284+
expect(res.headers.get('Link')).toContain(
283285
'<https://develop.sentry.dev/platforms/apple/cocoa/>; rel="canonical"'
284286
);
285287
});
286288

287-
it('does not add Link header for non-.md paths', async () => {
289+
it('uses the Markdown URL itself as canonical for /sitemap.md', async () => {
290+
const {middleware} = await importMiddleware({});
291+
const res = middleware(makeRequest('/sitemap.md'));
292+
expect(res.headers.get('Link')).toContain(
293+
'<https://docs.sentry.io/sitemap.md>; rel="canonical"'
294+
);
295+
});
296+
297+
it('adds Vary: Accept to .md responses', async () => {
298+
const {middleware} = await importMiddleware({});
299+
const res = middleware(makeRequest('/platforms/apple/cocoa.md'));
300+
expect(res.headers.get('Vary')).toBe('Accept');
301+
});
302+
});
303+
304+
describe('HTML pages advertise their Markdown version', () => {
305+
it('links the Markdown export and llms.txt', async () => {
288306
const {middleware} = await importMiddleware({});
289307
const res = middleware(makeRequest('/platforms/apple/cocoa/'));
290-
expect(res.headers.get('Link')).toBeNull();
308+
expect(res.headers.get('Link')).toBe(
309+
'<https://docs.sentry.io/platforms/apple/cocoa.md>; rel="alternate"; type="text/markdown", ' +
310+
'<https://docs.sentry.io/llms.txt>; rel="describedby"'
311+
);
312+
});
313+
314+
it('maps the root page to /index.md', async () => {
315+
const {middleware} = await importMiddleware({});
316+
const res = middleware(makeRequest('/'));
317+
expect(res.headers.get('Link')).toContain(
318+
'<https://docs.sentry.io/index.md>; rel="alternate"; type="text/markdown"'
319+
);
291320
});
292321
});
293322

@@ -318,3 +347,44 @@ describe('wantsMarkdownViaAccept: text/plain no longer triggers markdown', () =>
318347
expect(res.headers.get('x-middleware-rewrite')).toContain('.md');
319348
});
320349
});
350+
351+
describe('content negotiation on page URLs', () => {
352+
function pageRequest(headers: Record<string, string>): NextRequest {
353+
return new NextRequest(new URL('/platforms/apple/cocoa/', 'http://localhost:3000'), {
354+
headers,
355+
});
356+
}
357+
358+
it('serves Markdown with Vary and canonical headers', async () => {
359+
const {middleware} = await importMiddleware({});
360+
const res = middleware(pageRequest({Accept: 'text/markdown, text/html, */*'}));
361+
expect(res.headers.get('x-middleware-rewrite')).toContain(
362+
'/platforms/apple/cocoa.md'
363+
);
364+
expect(res.headers.get('Vary')).toBe('Accept');
365+
expect(res.headers.get('Link')).toBe(
366+
'<https://docs.sentry.io/platforms/apple/cocoa/>; rel="canonical", ' +
367+
'<https://docs.sentry.io/llms.txt>; rel="describedby"'
368+
);
369+
});
370+
371+
it('serves HTML when the client ranks HTML above Markdown', async () => {
372+
const {middleware} = await importMiddleware({});
373+
const res = middleware(pageRequest({Accept: 'text/html, text/markdown;q=0.9'}));
374+
expect(res.headers.get('x-middleware-rewrite')).toBeNull();
375+
});
376+
377+
it('serves Markdown to a recognized AI agent with no format preference', async () => {
378+
const {middleware} = await importMiddleware({});
379+
const res = middleware(pageRequest({'User-Agent': 'Claude-User', Accept: '*/*'}));
380+
expect(res.headers.get('x-middleware-rewrite')).toContain('.md');
381+
});
382+
383+
it('serves HTML to a recognized AI agent that asks for HTML', async () => {
384+
const {middleware} = await importMiddleware({});
385+
const res = middleware(
386+
pageRequest({'User-Agent': 'ChatGPT-User/1.0', Accept: 'text/html,*/*;q=0.8'})
387+
);
388+
expect(res.headers.get('x-middleware-rewrite')).toBeNull();
389+
});
390+
});

‎middleware.ts‎

Lines changed: 57 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import * as Sentry from '@sentry/nextjs';
22
import type {NextRequest} from 'next/server';
33
import {NextResponse, userAgent} from 'next/server';
4-
import {canonicalPath} from 'sentry-docs/canonical';
4+
import {canonicalPath, markdownExportPath} from 'sentry-docs/canonical';
55
import {DOCS_ORIGIN, isDeveloperDocs} from 'sentry-docs/docsSite.mjs';
6+
import {formatPreference, shouldServeMarkdown} from 'sentry-docs/lib/contentNegotiation';
67
import {
78
AI_AGENT_PATTERN,
89
matchPattern,
@@ -11,6 +12,12 @@ import {
1112

1213
const CANONICAL_HOST = new URL(DOCS_ORIGIN).hostname;
1314

15+
// llms.txt covers every page on the site (llmstxt.org link relation).
16+
const LLMS_TXT_LINK = `<${DOCS_ORIGIN}/llms.txt>; rel="describedby"`;
17+
18+
// Markdown-only resources with no HTML page; they are their own canonical URL.
19+
const MARKDOWN_ONLY_PATHS = new Set(['/sitemap.md']);
20+
1421
// sentry-for-ai-evals compares a PR's docs with the docs at its merge base, which it reads
1522
// from that commit's production build URL. It sends this header so the build serves its
1623
// own pages instead of redirecting to the canonical host.
@@ -175,15 +182,6 @@ function recordClassification(
175182
// don't send Permanent Redirects (301) in dev mode - it gets cached for "localhost" by the browser
176183
const redirectStatusCode = process.env.NODE_ENV === 'development' ? 302 : 301;
177184

178-
/**
179-
* Detects if the user agent belongs to an AI/LLM tool or development environment
180-
* that would benefit from markdown format.
181-
* Uses shared AI_AGENT_PATTERN from trafficClassification.ts.
182-
*/
183-
function isAIOrDevTool(userAgentString: string): boolean {
184-
return AI_AGENT_PATTERN.test(userAgentString);
185-
}
186-
187185
/**
188186
* Traffic classification for metrics tracking.
189187
* Uses Next.js userAgent() for enhanced bot detection plus custom AI agent patterns.
@@ -229,33 +227,6 @@ function classifyTraffic(request: NextRequest): {
229227
};
230228
}
231229

232-
/**
233-
* Detects if client wants markdown via Accept header (standards-compliant).
234-
* Only matches explicit markdown MIME types — not text/plain, which is too broad
235-
* and matches clients like Axios (`Accept: application/json, text/plain, *\/\/`).
236-
*/
237-
function wantsMarkdownViaAccept(acceptHeader: string): boolean {
238-
return (
239-
acceptHeader.includes('text/markdown') || acceptHeader.includes('text/x-markdown')
240-
);
241-
}
242-
243-
/**
244-
* Detects if client wants markdown via Accept header or user-agent
245-
*/
246-
function wantsMarkdown(request: NextRequest): boolean {
247-
const uaString = request.headers.get('user-agent') || '';
248-
const acceptHeader = request.headers.get('accept') || '';
249-
250-
// Strategy 1: Accept header content negotiation (standards-compliant)
251-
if (wantsMarkdownViaAccept(acceptHeader)) {
252-
return true;
253-
}
254-
255-
// Strategy 2: User-agent detection (fallback for tools that don't set Accept)
256-
return isAIOrDevTool(uaString);
257-
}
258-
259230
/**
260231
* Creates request headers with traffic classification for downstream consumption.
261232
* These headers are added to the REQUEST (not response) so tracesSampler can read them.
@@ -314,28 +285,31 @@ function mdToCanonicalPath(mdPathname: string): string {
314285
}
315286

316287
/**
317-
* Handles redirection to markdown versions for AI/LLM clients
288+
* Serves a page URL as HTML or Markdown (content negotiation), and advertises
289+
* the other representation on each response.
318290
*/
319291
const handleAIClientRedirect = (
320292
request: NextRequest,
321293
classification: TrafficClassification
322294
) => {
323-
const userAgentString = request.headers.get('user-agent') || '';
324295
const acceptHeader = request.headers.get('accept') || '';
325296
const url = request.nextUrl;
326297

327298
// Determine if this will be served as markdown
328299
const forceMarkdown = url.searchParams.get('format') === 'md';
329-
const clientWantsMarkdown = wantsMarkdown(request);
300+
const clientWantsMarkdown = shouldServeMarkdown(
301+
acceptHeader,
302+
classification.trafficType === 'ai_agent'
303+
);
330304
const willServeMarkdown =
331305
(clientWantsMarkdown || forceMarkdown) && !url.pathname.endsWith('.md');
332306

333307
// Determine detection method for logging
334-
const detectionMethod = wantsMarkdownViaAccept(acceptHeader)
335-
? 'Accept header'
336-
: isAIOrDevTool(userAgentString)
337-
? 'User-agent'
338-
: 'Manual';
308+
const detectionMethod = !clientWantsMarkdown
309+
? 'Manual'
310+
: formatPreference(acceptHeader) === 'markdown'
311+
? 'Accept header'
312+
: 'User-agent';
339313

340314
// Log user agent for debugging (only for non-static assets)
341315
if (
@@ -358,9 +332,11 @@ const handleAIClientRedirect = (
358332
// raw markdown. AI agents don't act on this header, so LLM ingestion is unaffected.
359333
if (url.pathname.endsWith('.md')) {
360334
const response = nextWithClassification(request, classification);
361-
response.headers.set(
362-
'Link',
363-
`<${DOCS_ORIGIN}${mdToCanonicalPath(url.pathname)}>; rel="canonical"`
335+
setMarkdownResponseHeaders(
336+
response,
337+
MARKDOWN_ONLY_PATHS.has(url.pathname)
338+
? url.pathname
339+
: mdToCanonicalPath(url.pathname)
364340
);
365341
return response;
366342
}
@@ -379,35 +355,55 @@ const handleAIClientRedirect = (
379355

380356
// Check for markdown request (Accept header, user-agent, or manual)
381357
if (clientWantsMarkdown || forceMarkdown) {
358+
const newUrl = url.clone();
359+
newUrl.pathname = markdownExportPath(url.pathname);
360+
382361
// Log the rewrite for debugging
383362
Sentry.logger.info('Markdown rewrite triggered', {
384363
urlPath: url.pathname,
385364
detectionMethod: forceMarkdown ? 'Manual format=md' : detectionMethod,
386-
targetUrl: url.pathname.replace(/\/+$/, '') + '.md',
365+
targetUrl: newUrl.pathname,
387366
});
388367

389-
// Create new URL with .md extension
390-
const newUrl = url.clone();
391-
// Handle root path and ensure proper .md extension
392-
let pathname = url.pathname === '/' ? '/index' : url.pathname;
393-
// Remove all trailing slashes if present, then add .md
394-
pathname = pathname.replace(/\/+$/, '') + '.md';
395-
newUrl.pathname = pathname;
396-
397368
// Clean up the format query parameter if it was used
398369
if (forceMarkdown) {
399370
newUrl.searchParams.delete('format');
400371
}
401372

402373
// Rewrite to serve markdown inline (same URL, different content)
403374
// The next.config.ts rewrite rule maps *.md to /md-exports/*.md
404-
return rewriteWithClassification(request, newUrl, classification);
375+
const response = rewriteWithClassification(request, newUrl, classification);
376+
setMarkdownResponseHeaders(response, canonicalPath(url.pathname));
377+
return response;
405378
}
406379

407-
// Default: pass through with traffic classification headers
408-
return nextWithClassification(request, classification);
380+
// Default: serve HTML, and point agents at the Markdown version and llms.txt
381+
// (llmstxt.org link relations, also rendered as <link> tags in the page head).
382+
// No `Vary` here: the App Router page renderer replaces it on HTML responses.
383+
const response = nextWithClassification(request, classification);
384+
response.headers.set(
385+
'Link',
386+
[
387+
`<${DOCS_ORIGIN}${markdownExportPath(url.pathname)}>; rel="alternate"; type="text/markdown"`,
388+
LLMS_TXT_LINK,
389+
].join(', ')
390+
);
391+
return response;
409392
};
410393

394+
/**
395+
* Headers for every Markdown response: `Vary: Accept` so caches keep the HTML
396+
* and Markdown versions of a URL apart, a canonical link to the HTML page, and
397+
* a link to llms.txt.
398+
*/
399+
function setMarkdownResponseHeaders(response: NextResponse, htmlPath: string): void {
400+
response.headers.set('Vary', 'Accept');
401+
response.headers.set(
402+
'Link',
403+
[`<${DOCS_ORIGIN}${htmlPath}>; rel="canonical"`, LLMS_TXT_LINK].join(', ')
404+
);
405+
}
406+
411407
const handleRedirects = (request: NextRequest) => {
412408
const urlPath = request.nextUrl.pathname;
413409

@@ -463,7 +459,7 @@ function toMarkdownDestination(destination: string): string {
463459
return destination;
464460
}
465461
const [path, hash] = destination.split('#');
466-
const mdPath = `${path.replace(/\/+$/, '') || '/index'}.md`;
462+
const mdPath = markdownExportPath(path);
467463
return hash === undefined ? mdPath : `${mdPath}#${hash}`;
468464
}
469465

0 commit comments

Comments
 (0)