Files
supabase/apps/docs/features/docs/GuidesMdx.utils.tsx
T
Miranda Limonczenko 86f3a98399 fix(docs): stop reporting guide 404s to Sentry, redirect missing paths (#50279)
Closes DOCS-1388

## Problem

Expected guide-path 404s were reported to Sentry as errors. They made up
roughly 246k events and nearly all Docs volume, with 0 users impacted.

The cause is a type check that never matched.
`getGuidesMarkdownInternal` tested `error.cause instanceof
FileNotFoundError`, but `GuideModelLoader.fromFs` rethrows
`FileNotFoundError` directly and sets `cause` to the underlying `ENOENT`
error. Every missing guide path fell through to the `else` branch and
hit `Sentry.captureException`.

Nine storage section paths and `database/postgrest` also 404 in
production. They are section `url` values in the nav config with no
landing page and no redirect. They are not reachable from the sidebar,
because a nav item with children renders as an accordion button, so the
traffic is inbound links and crawlers.

## Solution

- Check the error itself as well as its cause, so expected 404s take the
quiet branch.
- Add `ignoreErrors` for `FileNotFound` to `sentry.server.config.ts`,
matching the filtering the client config already does.
- Redirect nine storage section paths to their first child page,
following the existing `storage/cdn` and `storage/uploads` pattern.
- Redirect `database/postgrest` to the Data API guide. The path has no
git history, so its 27k hits are external inbound links.
- Add the missing leading slash to the `storage/access-control`
destination. It resolves correctly today, so this is a cleanup, not a
fix.

## Redirect previews

Redirects are served by the `www` config, so the **Redirect** column
uses the www preview. The www preview cannot render `/docs/**` pages, so
each link lands on a 404 after the hop. That is expected. Check the
`Location` header, or use the **Destination** column to confirm the page
itself.

| Source | Redirect | Destination |
| :--- | :--- | :--- |
| `/docs/guides/storage/production` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/production)
|
[storage/production/scaling](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/production/scaling)
|
| `/docs/guides/storage/security` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/security)
|
[storage/security/ownership](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/security/ownership)
|
| `/docs/guides/storage/serving` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/serving)
|
[storage/serving/downloads](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/serving/downloads)
|
| `/docs/guides/storage/management` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/management)
|
[storage/management/copy-move-objects](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/management/copy-move-objects)
|
| `/docs/guides/storage/s3` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/s3)
|
[storage/s3/authentication](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/s3/authentication)
|
| `/docs/guides/storage/debugging` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/debugging)
|
[storage/debugging/logs](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/debugging/logs)
|
| `/docs/guides/storage/schema` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/schema)
|
[storage/schema/design](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/schema/design)
|
| `/docs/guides/storage/vector` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/vector)
|
[storage/vector/introduction](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/vector/introduction)
|
| `/docs/guides/storage/analytics/examples` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/analytics/examples)
|
[storage/analytics/examples/duckdb](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/analytics/examples/duckdb)
|
| `/docs/guides/database/postgrest` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/database/postgrest)
|
[api](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/api)
|
| `/docs/guides/storage/access-control` |
[test](https://zone-www-dot-com-git-docs-sentry-404s-and-guide-fa783f-supabase.vercel.app/docs/guides/storage/access-control)
|
[storage/security/access-control](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/security/access-control)
|

All eleven return `308` on the www preview with the `Location` shown in
the Destination column. Every destination returns `200`.

## Manual testing

1. Open any **Redirect** link above. The URL changes to the Destination
path, confirming the redirect fires.
2. Open any **Destination** link. The page renders.
3. Confirm the sources 404 on production today, for example
`https://supabase.com/docs/guides/storage/production`.
4. On the [docs
preview](https://docs-git-docs-sentry-404s-and-guide-redirects-supabase.vercel.app/docs/guides/storage/schema),
request a missing guide path and check the deployment logs. The line
reads `Could not read Markdown at path`, not `Error processing Markdown
file at path`. The second form is the branch that calls
`Sentry.captureException`.
2026-09-11 14:05:24 -07:00

221 lines
7.1 KiB
TypeScript

import { readdir } from 'node:fs/promises'
import { extname, join, relative, sep } from 'node:path'
import * as Sentry from '@sentry/nextjs'
import { extractMessageFromAnyError, FileNotFoundError } from '~/app/api/utils'
import { pluckPromise } from '~/features/helpers.fn'
import { cache_fullProcess_withDevCacheBust, existsFile } from '~/features/helpers.fs'
import type { OrPromise } from '~/features/helpers.types'
import { generateOpenGraphImageMeta } from '~/features/seo/openGraph'
import { BASE_PATH } from '~/lib/constants'
import { getCustomContent } from '~/lib/custom-content/getCustomContent'
import { GUIDES_DIRECTORY, isValidGuideFrontmatter, type GuideFrontmatter } from '~/lib/docs'
import { mdAlternate } from '~/lib/md-alternates'
import { GuideModelLoader } from '~/resources/guide/guideModelLoader'
import { fromMarkdown } from 'mdast-util-from-markdown'
import { gfmFromMarkdown } from 'mdast-util-gfm'
import { gfm } from 'micromark-extension-gfm'
import { type Metadata, type ResolvingMetadata } from 'next'
import { notFound } from 'next/navigation'
import { newEditLink } from './GuidesMdx.template'
import { checkGuidePageEnabled } from './NavigationPageStatus.utils'
const { metadataTitle } = getCustomContent(['metadata:title'])
const PUBLISHED_SECTIONS = [
'ai',
'api',
'auth',
'cron',
'database',
'deployment',
'functions',
'getting-started',
'graphql',
'integrations',
'local-development',
'observability',
'platform',
'queues',
'realtime',
'resources',
'security',
'self-hosting',
'storage',
] as const
const getGuidesMarkdownInternal = async (slug: string[]) => {
const relPath = slug.join(sep).replace(/\/$/, '')
const fullPath = join(GUIDES_DIRECTORY, relPath + '.mdx')
const guidesPath = `/guides/${slug.join('/')}`
/**
* SAFETY CHECK:
* Prevent accessing anything outside of published sections and GUIDES_DIRECTORY
*/
if (
!fullPath.startsWith(GUIDES_DIRECTORY) ||
!PUBLISHED_SECTIONS.some((section) => relPath.startsWith(section))
) {
notFound()
}
/**
* DISABLED PAGE CHECK:
* Check if this page is disabled in the navigation configuration
*/
if (!checkGuidePageEnabled(guidesPath)) {
console.log('Page is disabled: %s', guidesPath)
notFound()
}
try {
const guide = (await GuideModelLoader.fromFs(relative(GUIDES_DIRECTORY, fullPath))).unwrap()
const content = guide.content ?? ''
const meta = guide.metadata ?? {}
if (!isValidGuideFrontmatter(meta)) {
throw Error(`Type of frontmatter is not valid for path: ${fullPath}`)
}
const { editLink: editLinkOverride, ...restMeta } = meta
const editLink = newEditLink(
editLinkOverride ?? `supabase/supabase/blob/master/apps/docs/content/guides/${relPath}.mdx`
)
return {
pathname: `/guides/${slug.join('/')}` satisfies `/${string}`,
meta: restMeta,
content,
editLink,
}
} catch (error: unknown) {
// `fromFs` rethrows FileNotFoundError directly, so check the error itself
// as well as its cause.
if (
error instanceof FileNotFoundError ||
(error instanceof Error && error.cause instanceof FileNotFoundError)
) {
// Not using console.error because this includes pages that are genuine
// 404s and clutters up the logs
console.log('Could not read Markdown at path: %s', fullPath)
} else {
console.error(
'Error processing Markdown file at path: %s:\n\t%s',
fullPath,
extractMessageFromAnyError(error)
)
Sentry.captureException(error)
}
notFound()
}
}
/**
* Caching this for the entire process is fine because the Markdown content is
* baked into each deployment and cannot change. There's also nothing sensitive
* here: this is just reading the public MDX files from the codebase.
*/
const getGuidesMarkdown = cache_fullProcess_withDevCacheBust(
getGuidesMarkdownInternal,
GUIDES_DIRECTORY,
(filename: string) => JSON.stringify([filename.replace(/\.mdx$/, '').split(sep)])
)
const genGuidesStaticParams = (directory?: string) => async () => {
const promises = directory
? (await readdir(join(GUIDES_DIRECTORY, directory), { recursive: true }))
.filter((file) => extname(file) === '.mdx' && !file.split(sep).at(-1)?.startsWith('_'))
.map((file) => ({ slug: file.replace(/\.mdx$/, '').split(sep) }))
.concat(
(await existsFile(join(GUIDES_DIRECTORY, `${directory}.mdx`))) ? [{ slug: [] }] : []
)
: PUBLISHED_SECTIONS.map(async (section) =>
(await readdir(join(GUIDES_DIRECTORY, section), { recursive: true }))
.filter((file) => extname(file) === '.mdx' && !file.split(sep).at(-1)?.startsWith('_'))
.map((file) => ({
slug: [section, ...file.replace(/\.mdx$/, '').split(sep)],
}))
.concat(
(await existsFile(join(GUIDES_DIRECTORY, `${section}.mdx`)))
? [{ slug: [section] }]
: []
)
)
// Flattening earlier will not work because there is nothing to flatten
// until the promises resolve.
const allParams = (await Promise.all(promises)).flat()
/**
* Filter out disabled pages from static generation
*/
const enabledParams = allParams.filter((param) => {
const guidesPath = `/guides/${directory ? `${directory}/` : ''}${param.slug.join('/')}`
const isEnabled = checkGuidePageEnabled(guidesPath)
if (!isEnabled) {
console.log('Excluding disabled page from static generation: %s', guidesPath)
}
return isEnabled
})
return enabledParams
}
const genGuideMeta =
<Params,>(
generate: (params: Params) => OrPromise<{ meta: GuideFrontmatter; pathname: `/${string}` }>
) =>
async (props: { params: Promise<Params> }, parent: ResolvingMetadata): Promise<Metadata> => {
const params = await props.params
const [parentAlternates, parentOg, { meta, pathname }] = await Promise.all([
pluckPromise(parent, 'alternates'),
pluckPromise(parent, 'openGraph'),
generate(params),
])
// Pathname has form `/guides/(section)/**`
const ogType = pathname.split('/')[2]
return {
title: `${meta.title} | ${metadataTitle || 'Supabase'}`,
description: meta.description || meta.subtitle,
// @ts-ignore
alternates: {
...parentAlternates,
canonical: meta.canonical || `${BASE_PATH}${pathname}`,
types: {
...(parentAlternates?.types ?? {}),
...mdAlternate(pathname.replace(/^\/guides\//, '')),
},
},
openGraph: {
...parentOg,
url: `${BASE_PATH}${pathname}`,
images: generateOpenGraphImageMeta({
type: ogType,
title: meta.title,
description: meta.description,
}),
},
}
}
function removeRedundantH1(content: string) {
const mdxTree = fromMarkdown(content, 'utf-8', {
extensions: [gfm()],
mdastExtensions: [gfmFromMarkdown()],
})
const maybeH1 = mdxTree.children[0]
if (maybeH1 && maybeH1.type === 'heading' && maybeH1.depth === 1) {
content = content.slice(maybeH1.position?.end?.offset)
}
return content
}
export { genGuideMeta, genGuidesStaticParams, getGuidesMarkdown, removeRedundantH1 }