diff --git a/apps/docs/app/api/search_v2/content.ts b/apps/docs/app/api/search_v2/content.ts
new file mode 100644
index 00000000000..ab2fd484ade
--- /dev/null
+++ b/apps/docs/app/api/search_v2/content.ts
@@ -0,0 +1,41 @@
+import { BASE_PATH, IS_DEV, IS_PRODUCTION, PROD_URL } from '~/lib/constants'
+
+/**
+ * Resolves the docs base URL (origin + base path) from trusted sources only, so the Host header
+ * can't redirect the fetches made for `content=true` (SSRF). The request origin is used in local
+ * development only.
+ */
+export function resolveDocsBaseUrl(requestUrl: string): string | undefined {
+ if (IS_PRODUCTION) return PROD_URL
+ if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}${BASE_PATH}`
+ if (process.env.NEXT_PUBLIC_SITE_URL) return `${process.env.NEXT_PUBLIC_SITE_URL}${BASE_PATH}`
+ if (IS_DEV) return `${new URL(requestUrl).origin}${BASE_PATH}`
+ return undefined
+}
+
+/**
+ * Fetches the markdown export of a page (`/.md`). Returns null when it can't be
+ * loaded, including pages with no markdown export (only guides have one).
+ */
+export async function fetchMarkdown(
+ baseUrl: string | undefined,
+ slug: string
+): Promise {
+ const segments = slug.split('/')
+ if (!baseUrl || segments[0] !== 'guides' || segments.some((s) => !s || s === '.' || s === '..')) {
+ return null
+ }
+
+ const url = `${baseUrl}/${segments.map(encodeURIComponent).join('/')}.md`
+ try {
+ const response = await fetch(url)
+ if (!response.ok) {
+ console.warn(`Failed to fetch docs content from ${url}: ${response.status}`)
+ return null
+ }
+ return await response.text()
+ } catch (error) {
+ console.warn(`Failed to fetch docs content from ${url}:`, error)
+ return null
+ }
+}
diff --git a/apps/docs/app/api/search_v2/route.test.ts b/apps/docs/app/api/search_v2/route.test.ts
new file mode 100644
index 00000000000..e9b0a4b4c5f
--- /dev/null
+++ b/apps/docs/app/api/search_v2/route.test.ts
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const rpc = vi.fn()
+vi.mock('~/scripts/search_v2/supabase', () => ({
+ SEARCH_FUNCTION: 'docs_search_v2',
+ createSupabaseClient: () => ({ rpc }),
+}))
+vi.mock('@sentry/nextjs', () => ({ captureException: vi.fn() }))
+vi.mock('~/lib/constants', () => ({
+ BASE_PATH: '/docs',
+ IS_DEV: false,
+ IS_PRODUCTION: true,
+ PROD_URL: 'https://supabase.com/docs',
+}))
+
+const { GET } = await import('./route')
+
+const guideRow = { slug: 'guides/auth/users', page_title: 'Users', heading: 'Users', score: 3500 }
+const referenceRow = { slug: 'reference/javascript/auth-signup', page_title: 'signUp', score: 3400 }
+
+const search = (params: string) =>
+ GET(new Request(`https://supabase.com/docs/api/search_v2?${params}`) as never)
+
+describe('GET /api/search_v2', () => {
+ beforeEach(() => {
+ rpc.mockReset()
+ vi.unstubAllGlobals()
+ })
+
+ it('rejects a missing query', async () => {
+ expect((await search('')).status).toBe(400)
+ expect(rpc).not.toHaveBeenCalled()
+ })
+
+ it('returns the rows as is, without fetching content, by default', async () => {
+ rpc.mockResolvedValue({ data: [guideRow], error: null })
+ const fetch = vi.fn()
+ vi.stubGlobal('fetch', fetch)
+
+ const response = await search('q=users&limit=3')
+
+ expect(rpc).toHaveBeenCalledWith('docs_search_v2', { query_text: 'users', match_limit: 3 })
+ expect(await response.json()).toEqual([guideRow])
+ expect(fetch).not.toHaveBeenCalled()
+ })
+
+ it('adds the markdown of guides when content=true', async () => {
+ rpc.mockResolvedValue({ data: [guideRow], error: null })
+ const fetch = vi.fn(async () => new Response('# Users'))
+ vi.stubGlobal('fetch', fetch)
+
+ const results = await (await search('q=users&content=true')).json()
+
+ expect(fetch).toHaveBeenCalledWith('https://supabase.com/docs/guides/auth/users.md')
+ expect(results).toEqual([{ ...guideRow, content: '# Users' }])
+ })
+
+ it('sets content to null for pages with no markdown or that fail to load', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const missing = { ...guideRow, slug: 'guides/missing' }
+ rpc.mockResolvedValue({ data: [referenceRow, missing], error: null })
+ const fetch = vi.fn(async () => new Response('', { status: 404 }))
+ vi.stubGlobal('fetch', fetch)
+
+ const results = await (await search('q=x&content=true')).json()
+
+ // reference pages have no markdown export, so they are not fetched at all
+ expect(fetch).toHaveBeenCalledTimes(1)
+ expect(results.map((r: { content: string | null }) => r.content)).toEqual([null, null])
+ })
+
+ it('returns 500 when the query fails', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ rpc.mockResolvedValue({ data: null, error: { message: 'boom' } })
+ expect((await search('q=x')).status).toBe(500)
+ })
+})
diff --git a/apps/docs/app/api/search_v2/route.ts b/apps/docs/app/api/search_v2/route.ts
index 3458196c98d..e1b1a153be2 100644
--- a/apps/docs/app/api/search_v2/route.ts
+++ b/apps/docs/app/api/search_v2/route.ts
@@ -2,6 +2,7 @@ import * as Sentry from '@sentry/nextjs'
import { createSupabaseClient, SEARCH_FUNCTION } from '~/scripts/search_v2/supabase'
import { type NextRequest } from 'next/server'
+import { fetchMarkdown, resolveDocsBaseUrl } from './content'
import { corsHeaders } from './cors'
export const runtime = 'edge'
@@ -15,6 +16,7 @@ export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const query = searchParams.get('q')?.trim()
const limit = Number(searchParams.get('limit')) || 10
+ const includeContent = searchParams.get('content') === 'true'
if (!query) {
return Response.json({ error: 'Missing q parameter' }, { status: 400, headers: corsHeaders })
@@ -34,7 +36,19 @@ export async function GET(request: NextRequest) {
return Response.json({ error: error.message }, { status: 500, headers: corsHeaders })
}
- return Response.json(data, { headers: corsHeaders })
+ if (!includeContent) {
+ return Response.json(data, { headers: corsHeaders })
+ }
+
+ // Attach each page's markdown export; null when it has none or can't be loaded.
+ const baseUrl = resolveDocsBaseUrl(request.url)
+ const results = await Promise.all(
+ (data as { slug: string }[]).map(async (row) => ({
+ ...row,
+ content: await fetchMarkdown(baseUrl, row.slug),
+ }))
+ )
+ return Response.json(results, { headers: corsHeaders })
} catch (error) {
console.error('Error handling docs search v2 request:', error)
Sentry.captureException(error, { tags: { route: 'search_v2' } })
diff --git a/supabase/migrations/20261116120000_align_kb_search_with_docs_search_v2.sql b/supabase/migrations/20261116120000_align_kb_search_with_docs_search_v2.sql
new file mode 100644
index 00000000000..40fbf44d4f2
--- /dev/null
+++ b/supabase/migrations/20261116120000_align_kb_search_with_docs_search_v2.sql
@@ -0,0 +1,126 @@
+-- Align search_kb with docs_search_v2: same tiered matching algorithm, applied to public.kb_search.
+-- Same name, arguments and return columns as before, so the API route and client are unchanged.
+-- Execution rights are unchanged too: only service_role can call it.
+--
+-- Differences from the previous search_kb:
+-- * No IDF-weighted scoring and no minimum-score cutoff.
+-- * Falls back to OR matching and then to typo-tolerant trigram matching when the stricter
+-- tiers return nothing.
+-- * Partial words ("edg", "edge fun") match as prefixes.
+
+create extension if not exists pg_trgm with schema extensions;
+
+create index if not exists kb_search_page_title_trgm_idx
+ on public.kb_search using gin (page_title extensions.gin_trgm_ops);
+create index if not exists kb_search_heading_trgm_idx
+ on public.kb_search using gin (heading extensions.gin_trgm_ops);
+
+-- Matches are tiered, and score bands keep a better tier above every match of a lower tier:
+-- strict (3000-3999) every term is a whole word (websearch_to_tsquery)
+-- prefix (2000-2999) every term is the start of a word ("edge fun" => "edge functions")
+-- or (1000-1999) any term matches, only when strict and prefix return nothing
+-- trigram (0-899) typo-tolerant match on page title or heading, only when all of the above
+-- return nothing
+-- Within a tier the score is ts_rank_cd normalised to 0..1 (normalization flag 32 => rank / (rank + 1)).
+--
+-- search_path is empty (as in the previous search_kb), so everything outside pg_catalog is
+-- schema-qualified, including the pg_trgm functions and operators.
+create or replace function public.search_kb(query_text text, match_limit int default 10)
+returns table (
+ slug text,
+ page_title text,
+ heading text,
+ heading_level smallint,
+ heading_path text[],
+ excerpt text,
+ score int
+)
+language sql
+stable
+set search_path = ''
+-- Minimum similarity for the trigram tier (pg_trgm default is 0.6).
+set pg_trgm.word_similarity_threshold = '0.4'
+as $$
+ with words as (
+ -- Lowercase alphanumeric words only, so the terms are safe to put in a tsquery.
+ select w
+ from regexp_split_to_table(
+ lower(regexp_replace(coalesce(query_text, ''), '[^[:alnum:]]+', ' ', 'g')),
+ '\s+'
+ ) as w
+ where w <> ''
+ ),
+ q as (
+ select
+ websearch_to_tsquery('english', query_text) as strict_q,
+ -- English stop words ("how", "to", "the") are dropped when the query is parsed.
+ to_tsquery('english', (select string_agg(w || ':*', ' & ') from words)) as prefix_q,
+ to_tsquery('english', (select string_agg(w || ':*', ' | ') from words)) as or_q
+ ),
+ strict_hits as (
+ select
+ d.slug, d.page_title, d.heading, d.heading_level, d.heading_path, d.excerpt,
+ 3000 + round(ts_rank_cd(d.fts, q.strict_q, 32) * 999)::int as score
+ from public.kb_search d, q
+ where d.fts @@ q.strict_q
+ ),
+ prefix_hits as (
+ select
+ d.slug, d.page_title, d.heading, d.heading_level, d.heading_path, d.excerpt,
+ 2000 + round(ts_rank_cd(d.fts, q.prefix_q, 32) * 999)::int as score
+ from public.kb_search d, q
+ where d.fts @@ q.prefix_q
+ ),
+ primary_hits as (
+ select * from strict_hits
+ union all
+ select * from prefix_hits
+ ),
+ or_hits as (
+ select
+ d.slug, d.page_title, d.heading, d.heading_level, d.heading_path, d.excerpt,
+ 1000 + round(ts_rank_cd(d.fts, q.or_q, 32) * 999)::int as score
+ from public.kb_search d, q
+ where d.fts @@ q.or_q
+ and not exists (select 1 from primary_hits)
+ ),
+ trigram_hits as (
+ select
+ d.slug, d.page_title, d.heading, d.heading_level, d.heading_path, d.excerpt,
+ round(
+ greatest(
+ extensions.word_similarity(query_text, d.page_title),
+ extensions.word_similarity(query_text, d.heading)
+ ) * 899
+ )::int as score
+ from public.kb_search d
+ where (
+ query_text operator(extensions.<%) d.page_title
+ or query_text operator(extensions.<%) d.heading
+ )
+ and not exists (select 1 from primary_hits)
+ and not exists (select 1 from or_hits)
+ ),
+ ranked as (
+ select * from primary_hits
+ union all
+ select * from or_hits
+ union all
+ select * from trigram_hits
+ ),
+ -- A page can have several matching sections; keep only its best-scoring one so the
+ -- same route doesn't take up multiple slots in the results.
+ best_per_page as (
+ select distinct on (r.slug) r.*
+ from ranked r
+ order by r.slug, r.score desc, r.heading_level asc
+ )
+ select b.slug, b.page_title, b.heading, b.heading_level, b.heading_path, b.excerpt, b.score
+ from best_per_page b
+ order by b.score desc, b.heading_level asc, b.slug asc
+ limit greatest(1, least(coalesce(match_limit, 10), 100));
+$$;
+
+-- Re-asserted so the grants stay correct even if the function is ever recreated.
+revoke execute on function public.search_kb(text, int) from public, anon, authenticated;
+grant execute on function public.search_kb(text, int) to service_role;