Files
supabase/apps/docs/proxy.ts
Miranda Limonczenko e44837c256 feat(docs): point every docs page at llms.txt in HTML and markdown (#53965)
Closes DOCS-1756

## Problem

No docs page tells an agent that `llms.txt` exists or that a markdown
version is available. Agents that send `Accept: text/markdown` already
get markdown, but agents that fetch HTML have no signal to try the
markdown path.


## Solution

- **HTML:** add a visually hidden directive as the first child of
`<body>` in the root layout, so it comes before the navigation on every
guide and reference page. It links to
`https://supabase.com/docs/llms.txt` and says guide pages have a
markdown version at the same path with `.md` appended, before any query
string or fragment. It's `sr-only` and `aria-hidden`, and the link has
`tabindex="-1"`.
- **Crawler HTML:** bot requests for SDK reference pages are rewritten
to `/api/crawlers`, which skips the root layout. The same directive goes
before its `<nav>`.
- **Markdown:** add a sentence linking `llms.txt` to the "Note for AI
agents" blockquote in the guides markdown route. The agent feedback page
skips the feedback text to avoid linking to itself, but it keeps the
`llms.txt` line.
- Add `LLMS_TXT_URL` and `LLMS_TXT_DIRECTIVE_HTML` to
`common/markdown-affordance`, and reuse `LLMS_TXT_URL` in `proxy.ts`.

The directive limits the `.md` claim to guides, because reference `.md`
requests 404. It doesn't say `llms.txt` lists every page.

The link targets `/docs/llms.txt`, the docs index that AFDocs scores for
the `/docs` base URL. #53968 makes it a real file. Until that merges,
`/docs/llms.txt` 308-redirects to the site-wide `/llms.txt`, so the link
works in either merge order.

## Manual testing

1. Open a Vercel preview guide page and view source. Confirm the
`llms.txt` directive comes before the navigation markup.
2. Open a reference page and confirm the same.
3. Confirm the directive isn't visible and isn't tabbable.
4. Request a reference section page with a bot user agent, such as `curl
-A Googlebot`, and confirm the directive comes before `<nav>`.
5. Request a guide with `.md` appended and confirm the opening
blockquote links `llms.txt`.
6. Request `/docs/guides/ai-tools/agent-feedback.md` and confirm the
opening blockquote links `llms.txt`.
7. Run AFDocs against the preview and confirm `llms-txt-directive-html`
and `llms-txt-directive-md` pass.
2026-11-24 15:02:23 -08:00

150 lines
5.1 KiB
TypeScript

import { clientSdkIds } from '~/content/navigation.references'
import { IA_NAV_FLAG, iaNavRoutePrefix, isIaNavVariant } from '~/features/IaNav/constants'
import { BASE_PATH, PROD_URL } from '~/lib/constants'
import { MARKDOWN_CONTENT_TYPE } from '~/lib/md-alternates'
import MARKDOWN_SLUGS from '~/public/markdown/manifest.json'
import { LLMS_TXT_URL } from 'common/markdown-affordance'
import { negotiateMarkdown } from 'common/markdown-negotiation'
import { isbot } from 'isbot'
import { NextResponse, type NextRequest } from 'next/server'
const REFERENCE_PATH = `${BASE_PATH ?? ''}/reference`
const GUIDES_PATH = `${BASE_PATH ?? ''}/guides`
const GUIDES_MARKDOWN_SLUGS = new Set(MARKDOWN_SLUGS)
const REFERENCE_MARKDOWN_LIBS = new Set([...clientSdkIds, 'cli', 'api'])
const LLMS_FILE_NAMES: Record<string, string> = { javascript: 'js' }
function markdownUrl(section: string, lib: string | undefined) {
if (section !== 'reference' || !lib || !REFERENCE_MARKDOWN_LIBS.has(lib)) {
return LLMS_TXT_URL
}
return `https://supabase.com/llms/${LLMS_FILE_NAMES[lib] ?? lib}.txt`
}
function markdownNotFound(pathname: string) {
const relativePath = pathname.replace(`${BASE_PATH}/`, '').replace(/\.md$/, '')
const [section, lib] = relativePath.split('/')
const markdown = `# 404 Not Found
There is no markdown version of \`${BASE_PATH}/${relativePath}\`.
- HTML page: <${PROD_URL}/${relativePath}>
- Markdown: <${markdownUrl(section, lib)}>
`
return new NextResponse(markdown, {
status: 404,
headers: {
'Content-Type': MARKDOWN_CONTENT_TYPE,
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
},
})
}
function forcedVariantRewrite(url: URL, path: string) {
const variant = url.searchParams.get(IA_NAV_FLAG)
if (!isIaNavVariant(variant) || variant === 'control') return null
const rewriteUrl = new URL(url)
rewriteUrl.pathname = `${BASE_PATH ?? ''}${iaNavRoutePrefix(variant)}${path}`
return NextResponse.rewrite(rewriteUrl)
}
export function proxy(request: NextRequest) {
const url = new URL(request.url)
const { pathname } = url
if (pathname === (BASE_PATH || '/')) {
return forcedVariantRewrite(url, '') ?? NextResponse.next()
}
if (pathname.startsWith(GUIDES_PATH + '/')) {
const isMdSuffix = pathname.endsWith('.md')
const slug = pathname.replace(`${GUIDES_PATH}/`, '').replace(/\.md$/, '')
const decision = negotiateMarkdown(
{ acceptHeader: request.headers.get('accept') ?? '' },
{ hasMarkdownVariant: GUIDES_MARKDOWN_SLUGS.has(slug), isMarkdownSuffix: isMdSuffix }
)
if (decision === 'not-acceptable') {
return new NextResponse('Not Acceptable', {
status: 406,
headers: { 'Cache-Control': 'no-store', Vary: 'Accept' },
})
}
if (decision === 'markdown') {
const rewriteUrl = new URL(url)
rewriteUrl.pathname = `${BASE_PATH ?? ''}/api/guides-md/${slug}`
return NextResponse.rewrite(rewriteUrl)
}
const variantRewrite =
!isMdSuffix && GUIDES_MARKDOWN_SLUGS.has(slug)
? forcedVariantRewrite(url, `/guides/${slug}`)
: null
if (variantRewrite) return variantRewrite
}
// Reference pages have no per-page markdown yet, so every reference .md is a guess.
// Narrow this when per-page reference markdown ships, or it will 404 those files.
if (pathname.endsWith('.md')) {
return markdownNotFound(pathname)
}
if (!pathname.startsWith(REFERENCE_PATH)) {
return NextResponse.next()
}
if (isbot(request.headers.get('user-agent'))) {
let [, lib, maybeVersion, ...slug] = pathname.replace(REFERENCE_PATH, '').split('/')
if (clientSdkIds.includes(lib)) {
const version = /^v\d+$/.test(maybeVersion) ? maybeVersion : undefined
if (!version) {
slug = [maybeVersion, ...slug]
}
if (slug.length > 0) {
const rewriteUrl = new URL(url)
rewriteUrl.pathname = (BASE_PATH ?? '') + '/api/crawlers'
return NextResponse.rewrite(rewriteUrl)
}
}
}
const [, lib, maybeVersion] = pathname.replace(REFERENCE_PATH, '').split('/')
if (lib === 'cli') {
const rewritePath = [REFERENCE_PATH, 'cli'].join('/')
return NextResponse.rewrite(new URL(rewritePath, request.url))
}
// Spike (DOCS-1268): only the bare /reference/api needs normalizing now.
// /reference/api/<slug> has its own statically generated page — don't
// collapse it back to the monolith.
if (lib === 'api' && !maybeVersion) {
const rewritePath = [REFERENCE_PATH, 'api'].join('/')
return NextResponse.rewrite(new URL(rewritePath, request.url))
}
if (lib?.startsWith('self-hosting-')) {
const rewritePath = [REFERENCE_PATH, lib].join('/')
return NextResponse.rewrite(new URL(rewritePath, request.url))
}
if (clientSdkIds.includes(lib)) {
const version = /^v\d+$/.test(maybeVersion) ? maybeVersion : null
const rewritePath = [REFERENCE_PATH, lib, version].filter(Boolean).join('/')
return NextResponse.rewrite(new URL(rewritePath, request.url))
}
return NextResponse.next()
}
export const config = {
matcher: ['/', '/reference/:path*', '/guides/:path*'],
}