Files
supabase/apps/docs/app/api/revalidate/route.test.ts
Alexis Aguilar 44386580e3 feat(docs): upgrade to Next.js 16 (#52045)
## Problem

The docs site (`apps/docs`) is still on Next.js 15, which is close to
the end of its support window under the [Next.js support
policy](https://nextjs.org/support-policy). Resolves
[DOCS-1485](https://linear.app/supabase/issue/DOCS-1485/upgrade-the-docs-site-to-nextjs-16).

## Solution

Upgrades `apps/docs` to Next.js 16.3.6. The scope is limited to what
Next.js 16 requires, so existing routes, redirects, and responses stay
the same.

- **Dependencies:** `next` uses the workspace catalog, and `@next/mdx`
and `@next/bundle-analyzer` are bumped to 16.3.6.
- **Webpack:** `dev` and `build` run with `--webpack`, because the docs
config loads `.include`, `.toml`, and YAML files through webpack, and
the MDX remark plugins have non-serializable options.
- **Proxy:** `middleware.ts` is renamed to `proxy.ts`.
- **Cache revalidation:** `revalidateTag` is called with `{ expire: 0 }`
to keep immediate expiration.
- **Images:** `images.localPatterns` allows guide images with `?v=N`
cache-busting query strings. Without it, those pages return 500.
- **Scroll behavior:** `data-scroll-behavior="smooth"` on `<html>` keeps
route changes jumping to the top instantly.
- **Config:** the `eslint` key is removed from `next.config.mjs`, and
Sentry options use their new names.
- **`next-env.d.ts`:** gitignored, like in the other apps, because
Next.js 16 regenerates it differently for `dev` and `typegen`.

### Dependency on the marketing site upgrade

The docs chat edge function (`/api/ai/docs`) stays under the Vercel Edge
Function size limit because #52001
([FE-4673](https://linear.app/supabase/issue/FE-4673/upgrade-the-marketing-site-to-nextjs-16))
removed `js-tiktoken` from `ai-commands`. This branch is based on
`master` with that change.

## Known limitations

- `proxy.ts` runs on the Node.js runtime instead of edge.
- `nuqs` v1 doesn't declare support for Next.js 15 or 16. The
troubleshooting filters work on Next.js 16, but the dependency is
outside its supported range.
- `next/legacy/image` and `unstable_cache` are deprecated but still
supported.
- Tabs opened before the deploy keep running the Next.js 15 client. On
their next client-side navigation, the router loads the page in full
instead. Docs pages are prerendered, so these requests don't reach the
renderer or report errors to Sentry.

## Review instructions

1. Run `pnpm --filter=docs typecheck` and `pnpm --filter=docs
test:local`.
2. Run `pnpm dev:docs` and open a guide, a client library reference
page, and `/guides/troubleshooting` with a filter applied.
3. Check the Vercel preview against production docs: every sitemap URL
returns the same status code, and redirects, `.md` responses, search,
and the AI chat behave the same. A local production build already
matches production for the following:
   - All 2,564 sitemap URLs
- The redirects in `next.config.mjs`, except where a www redirect
handles the path first
   - `.md` negotiation, including the 406 response
   - Reference rewrites, including bot requests

Search and the AI chat need the preview, because they depend on
production data and keys.
4. Confirm the preview build has enough memory. Locally, `next build`
peaked at about 4 GB.

## Future work

- Upgrade `nuqs` to v2.
- Replace `next/legacy/image` with `next/image`.
- Replace `unstable_cache` with `use cache`.

## Checklist

Check all before review:

- [ ] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
2026-10-21 13:16:54 -07:00

191 lines
6.1 KiB
TypeScript

/* eslint-disable turbo/no-undeclared-env-vars */
import { createClient } from '@supabase/supabase-js'
import { revalidateTag } from 'next/cache'
import { headers } from 'next/headers'
import { NextRequest } from 'next/server'
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
import { _handleRevalidateRequest } from './route.utils'
// Mock Next.js modules
vi.mock('next/cache', () => ({
revalidateTag: vi.fn(),
}))
vi.mock('next/headers', () => ({
headers: vi.fn(),
}))
// Mock Supabase client
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(),
}))
describe('_handleRevalidateRequest', () => {
let mockDate: Date
let originalEnv: NodeJS.ProcessEnv
let mockSupabaseClient: {
rpc: Mock
from: Mock
}
beforeEach(() => {
// Store the original environment
originalEnv = { ...process.env }
// Mock environment variables
process.env.DOCS_REVALIDATION_KEYS = 'basic_key'
process.env.DOCS_REVALIDATION_OVERRIDE_KEYS = 'override_key,other_override_key'
process.env.NEXT_PUBLIC_SUPABASE_URL = 'http://localhost:3000'
process.env.SUPABASE_SECRET_KEY = 'secret_key'
// Silence intentional console errors for cleaner test output
vi.spyOn(console, 'error').mockImplementation(() => {})
// Mock current date
mockDate = new Date('2023-01-01T12:00:00Z')
vi.setSystemTime(mockDate)
// Setup mock Supabase client
mockSupabaseClient = {
rpc: vi.fn(),
from: vi.fn(() => ({
insert: vi.fn().mockResolvedValue({ error: null }),
})),
}
vi.mocked(createClient).mockReturnValue(mockSupabaseClient as any)
})
afterEach(() => {
process.env = originalEnv
vi.useRealTimers()
})
it('should return 401 if Authorization header is missing', async () => {
const request = new NextRequest('https://example.com', {
method: 'POST',
})
vi.mocked(headers).mockReturnValue(Promise.resolve(new Headers(request.headers)))
const response = await _handleRevalidateRequest(request)
expect(response.status).toBe(401)
expect(await response.text()).toBe('Missing Authorization header')
})
it('should return 401 if Authorization header is invalid', async () => {
const request = new NextRequest('https://example.com', {
method: 'POST',
headers: {
Authorization: 'Bearer invalid_token',
},
})
vi.mocked(headers).mockReturnValue(Promise.resolve(new Headers(request.headers)))
const response = await _handleRevalidateRequest(request)
expect(response.status).toBe(401)
expect(await response.text()).toBe('Invalid Authorization header')
})
it('should return 400 if request body is malformed', async () => {
const request = new NextRequest('https://example.com', {
method: 'POST',
headers: {
Authorization: 'Bearer basic_key',
},
body: JSON.stringify({ invalid: 'body' }),
})
vi.mocked(headers).mockReturnValue(Promise.resolve(new Headers(request.headers)))
const response = await _handleRevalidateRequest(request)
expect(response.status).toBe(400)
expect(await response.text()).toContain('Malformed request body')
})
it('should revalidate tags if request is valid with basic permissions', async () => {
const request = new NextRequest('https://example.com', {
method: 'POST',
headers: {
Authorization: 'Bearer basic_key',
},
body: JSON.stringify({ tags: ['graphql', 'wrappers'] }),
})
vi.mocked(headers).mockReturnValue(Promise.resolve(new Headers(request.headers)))
mockSupabaseClient.rpc.mockResolvedValue({ data: [] })
const response = await _handleRevalidateRequest(request)
expect(response.status).toBe(204)
expect(revalidateTag).toHaveBeenCalledTimes(2)
expect(revalidateTag).toHaveBeenCalledWith('graphql', { expire: 0 })
expect(revalidateTag).toHaveBeenCalledWith('wrappers', { expire: 0 })
})
it('should return 429 if last revalidation was less than 6 hours ago with basic permissions', async () => {
const request = new NextRequest('https://example.com', {
method: 'POST',
headers: {
Authorization: 'Bearer basic_key',
},
body: JSON.stringify({ tags: ['graphql'] }),
})
vi.mocked(headers).mockReturnValue(Promise.resolve(new Headers(request.headers)))
const fiveHoursAgo = new Date(mockDate.getTime() - 5 * 60 * 60 * 1000)
mockSupabaseClient.rpc.mockResolvedValue({
data: [{ created_at: fiveHoursAgo.toISOString() }],
})
const response = await _handleRevalidateRequest(request)
expect(response.status).toBe(429)
expect(await response.text()).toContain('revalidated within the last 6 hours')
})
it('should revalidate if last revalidation was more than 6 hours ago with basic permissions', async () => {
const request = new NextRequest('https://example.com', {
method: 'POST',
headers: {
Authorization: 'Bearer basic_key',
},
body: JSON.stringify({ tags: ['graphql'] }),
})
vi.mocked(headers).mockReturnValue(Promise.resolve(new Headers(request.headers)))
const sevenHoursAgo = new Date(mockDate.getTime() - 7 * 60 * 60 * 1000)
mockSupabaseClient.rpc.mockResolvedValue({
data: [{ created_at: sevenHoursAgo.toISOString() }],
})
const response = await _handleRevalidateRequest(request)
expect(response.status).toBe(204)
expect(revalidateTag).toHaveBeenCalledWith('graphql', { expire: 0 })
})
it('should revalidate regardless of last revalidation time with override permissions', async () => {
const request = new NextRequest('https://example.com', {
method: 'POST',
headers: {
Authorization: 'Bearer override_key',
},
body: JSON.stringify({ tags: ['graphql'] }),
})
vi.mocked(headers).mockReturnValue(Promise.resolve(new Headers(request.headers)))
const oneHourAgo = new Date(mockDate.getTime() - 1 * 60 * 60 * 1000)
mockSupabaseClient.rpc.mockResolvedValue({
data: [{ created_at: oneHourAgo.toISOString() }],
})
const response = await _handleRevalidateRequest(request)
expect(response.status).toBe(204)
expect(revalidateTag).toHaveBeenCalledWith('graphql', { expire: 0 })
})
})