fix: server-render /open-source repos and library docs code (#52655)

Two page templates still served their main content only after JavaScript
ran, so crawlers that don't run it never saw it. The /open-source repo
cards came from a GitHub fetch in a `useEffect`. The library docs
install command and the default code view on the client pages were
`dynamic(..., { ssr: false })`.

**Changed:**
- **/open-source repo cards render in the HTML**: I added
`getStaticProps` with hourly ISR that fetches the org repos once, keeps
only the repos the tabs list, and seeds `Repos`. Any failure (non-2xx,
timeout, unexpected body) falls back to `null`, which keeps today's
client fetch, and that result is cached for 60s so a rate-limited
regeneration heals quickly. I made counts format as `en-US` until
hydration so non-US browsers don't hit a hydration mismatch, and I
switched the star sort to a consistent comparator so ties hydrate in the
same order in every engine.
- **Library docs install command renders on the server**: I made the
app's `useLocalStorage` read storage in a layout effect instead of the
`useState` initializer, so `Command` no longer needs `ssr: false`.
Returning users who picked another package manager see npm until
hydration, then their choice, where before the box was empty until then.
- **Library docs code shows instead of "Loading code preview..."**: I
kept `CodeBlock` client-only because it reads the resolved theme, and I
changed its loading fallback to render the selected file's code in a
plain `<pre>`.

**Note:** the GitHub fetch is unauthenticated, since the www project has
no general-purpose GitHub token. If regeneration keeps getting
rate-limited, adding a read-only token to the www env is a few-line
follow-up.

## To test
Tested on the PR previews, compared with prod:
- [x] `curl -sL` /open-source with a Chrome user agent and strip
`<script>`, `<style>` and `<template>`: supabase, supabase-js,
supavisor, postgres and postgres-meta appear with their descriptions
(prod has no repo cards).
- [x] `curl -sL` /open-source and read the `__NEXT_DATA__` JSON: every
name in `repos` appears in the page's tabs.
- [x] On /open-source with the browser language set to German: the
Database tab shows the same cards in the same order as prod, counts use
German separators after load, the browser makes no GitHub API request,
and the console shows no hydration error.
- [x] Switch to the Auth and Other tabs: the same cards as prod. Repos
with equal star counts can appear in a different order.
- [x] `curl -sL` /library/docs/nextjs/client the same way:
`createBrowserClient` is present in a plain `<pre>` (prod shows "Loading
code preview...").
- [x] `curl -sL` a block page such as
/library/docs/nextjs/password-based-auth: the `npx shadcn@latest add`
command is present (prod has none).
- [x] On a block page, pick pnpm in the install command and reload: pnpm
stays selected, with no hydration error.
- [x] On /library/docs/nextjs/client after load, in light and dark
theme: the highlighted code block matches prod, with line numbers.
- [x] No hydration warnings in the console on any of these pages.

## Linear
- part of GROWTH-1416
This commit is contained in:
Pamela Chia authored and GitHub committed 2026-11-03 20:48:08 +08:00
1 parent 2dc0258b14
commit aad17d2ee2
6 files changed
+102 -42

No files matched your search

+21 -14
View File
@@ -2,20 +2,25 @@
import { File } from 'lucide-react'
import dynamic from 'next/dynamic'
import { useState } from 'react'
import { createContext, useContext, useState } from 'react'
import { cn, flattenTree, TreeView, TreeViewItem } from 'ui'
import type { CodeBlockLang } from 'ui-patterns/CodeBlock'
import { RegistryNode } from '@/lib/process-registry'
// next/dynamic passes no props to `loading`, so the fallback reads the code from context.
const PendingCodeContext = createContext('')
function PendingCode() {
const code = useContext(PendingCodeContext)
return (
<pre className="w-full min-h-0 min-w-0 flex-1 overflow-auto p-4 font-mono text-xs">{code}</pre>
)
}
const CodeBlock = dynamic(
() => import('ui-patterns/CodeBlock').then((module) => module.CodeBlock),
{
ssr: false,
loading: () => (
<div className="p-4 text-xs text-foreground-lighter">Loading code preview...</div>
),
}
{ ssr: false, loading: () => <PendingCode /> }
)
interface BlockItemCodeProps {
@@ -143,13 +148,15 @@ export function BlockItemCode({ files, embedded = false }: BlockItemCodeProps) {
{/* Code display area */}
{selectedFile?.content ? (
<CodeBlock
wrapperClassName="w-full min-h-0 min-w-0 flex-1"
className="h-full max-w-none w-full! flex-1 font-mono text-xs rounded-none border-none"
language={languageFor(selectedFile.name)}
>
{selectedFile?.content}
</CodeBlock>
<PendingCodeContext.Provider value={selectedFile.content}>
<CodeBlock
wrapperClassName="w-full min-h-0 min-w-0 flex-1"
className="h-full max-w-none w-full! flex-1 font-mono text-xs rounded-none border-none"
language={languageFor(selectedFile.name)}
>
{selectedFile?.content}
</CodeBlock>
</PendingCodeContext.Provider>
) : (
<div className="flex items-center justify-center h-full text-muted-foreground">
<div className="flex flex-col items-center gap-2">
+1 -5
View File
@@ -1,12 +1,8 @@
'use client'
import dynamic from 'next/dynamic'
import { Command } from './command'
import type { ShadcnFramework } from '@/lib/install-command'
//The dynamic import is to prevent the command component from being rendered on the server and cause hydration errors
const Command = dynamic(() => import('./command').then((mod) => mod.Command), { ssr: false })
interface BlockItemProps {
name: string
framework?: ShadcnFramework
@@ -1,21 +1,21 @@
// Reference: https://usehooks.com/useLocalStorage/
import { safeLocalStorage } from 'common'
import { useCallback, useState } from 'react'
import { useCallback, useLayoutEffect, useState } from 'react'
export function useLocalStorage<T>(key: string, initialValue: T) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState<T>(() => {
// safeLocalStorage handles SSR and unavailable storage (returns null);
// the try/catch here only guards JSON.parse against corrupt values.
const [storedValue, setStoredValue] = useState<T>(initialValue)
// Read after mount so the server render and the hydrating client render agree.
useLayoutEffect(() => {
const item = safeLocalStorage.getItem(key)
if (!item) return
try {
return item ? (JSON.parse(item) as T) : initialValue
setStoredValue(JSON.parse(item) as T)
} catch (error) {
console.warn(`Failed to parse localStorage value for "${key}"`, error)
return initialValue
}
})
}, [key])
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
+11 -2
View File
@@ -3,9 +3,18 @@ import { useSendTelemetryEvent } from '~/lib/telemetry'
import { Star } from 'lucide-react'
import { motion } from 'motion/react'
import Link from 'next/link'
import { useSyncExternalStore } from 'react'
const subscribeToNothing = () => () => {}
const RepoCard = ({ repo, activeTab, index }: { repo: any; activeTab: number; index: number }) => {
const sendTelemetryEvent = useSendTelemetryEvent()
const isHydrated = useSyncExternalStore(
subscribeToNothing,
() => true,
() => false
)
const countLocale = isHydrated ? undefined : 'en-US'
return (
<motion.div
key={`${activeTab}-${repo.name}`}
@@ -56,7 +65,7 @@ const RepoCard = ({ repo, activeTab, index }: { repo: any; activeTab: number; in
<p>{repo.full_name}</p>
<div className="flex items-center gap-3">
<div className="flex items-center gap-1">
<span>{repo.forks.toLocaleString()}</span>
<span>{repo.forks.toLocaleString(countLocale)}</span>
<svg
viewBox="0 0 16 16"
fill="none"
@@ -70,7 +79,7 @@ const RepoCard = ({ repo, activeTab, index }: { repo: any; activeTab: number; in
</svg>
</div>
<div className="flex items-center gap-1">
<span>{repo.stargazers_count.toLocaleString()}</span>
<span>{repo.stargazers_count.toLocaleString(countLocale)}</span>
<Star className="w-4 fill-foreground-lighter stroke-none" />
</div>
</div>
+16 -4
View File
@@ -48,6 +48,15 @@ const Tab = ({ isActive, label, icon, onClick }: TabProps) => (
</button>
)
export type GitHubRepo = {
name: string
description: string | null
html_url: string
full_name: string
forks: number
stargazers_count: number
}
export interface RepoTab {
label: string
icon?: string
@@ -56,6 +65,7 @@ export interface RepoTab {
interface Props {
tabs: RepoTab[]
initialRepos: GitHubRepo[] | null
}
enum SWIPER_STATE {
@@ -64,13 +74,15 @@ enum SWIPER_STATE {
END = 'END',
}
const Repos = ({ tabs }: Props) => {
const [repos, setRepos] = useState<any[] | null>(null)
const Repos = ({ tabs, initialRepos }: Props) => {
const [repos, setRepos] = useState<any[] | null>(initialRepos)
const [activeTab, setActiveTab] = useState(0)
const [apiSwiper, setApiSwiper] = useState(undefined)
const [swiperState, setSwiperState] = useState<SWIPER_STATE>(SWIPER_STATE.START)
useEffect(() => {
if (initialRepos) return
async function fetchOctoData() {
const { Octokit } = await import('@octokit/core')
const octokit = new Octokit()
@@ -84,7 +96,7 @@ const Repos = ({ tabs }: Props) => {
setRepos(res.data)
}
fetchOctoData()
}, [])
}, [initialRepos])
useEffect(() => {
if (!apiSwiper) return
@@ -99,7 +111,7 @@ const Repos = ({ tabs }: Props) => {
const activeTabRepos = repos
? repos
?.filter((repo) => tabs[activeTab].repos?.includes(repo.name))
?.sort((a, b) => (a.stargazers_count < b.stargazers_count ? 1 : -1))
?.sort((a, b) => b.stargazers_count - a.stargazers_count)
: []
return (
+45 -9
View File
@@ -1,19 +1,18 @@
import 'swiper/css'
import { useRouter } from 'next/router'
import { NextSeo } from 'next-seo'
import CTABanner from '~/components/CTABanner'
import DefaultLayout from '~/components/Layouts/Default'
import SectionContainer from '~/components/Layouts/SectionContainer'
import CTABanner from '~/components/CTABanner'
import OSSHero from '~/components/OpenSource/OSSHero'
import ProductHeaderCentered from '~/components/Sections/ProductHeaderCentered'
import Repos from '~/components/OpenSource/Repos'
import Repos, { type GitHubRepo } from '~/components/OpenSource/Repos'
import Sponsorships from '~/components/OpenSource/Sponsorships'
import ProductHeaderCentered from '~/components/Sections/ProductHeaderCentered'
import pageData from '~/data/open-source'
import type { GetStaticProps, InferGetStaticPropsType } from 'next'
import { NextSeo } from 'next-seo'
import { useRouter } from 'next/router'
const OpenSource = () => {
const OpenSource = ({ repos }: InferGetStaticPropsType<typeof getStaticProps>) => {
const router = useRouter()
const meta_title = pageData.metaTitle || 'Open Source | Supabase'
@@ -43,7 +42,7 @@ const OpenSource = () => {
</SectionContainer>
<OSSHero />
<SectionContainer className="pt-0!">
<Repos tabs={pageData.repo_tabs} />
<Repos tabs={pageData.repo_tabs} initialRepos={repos} />
</SectionContainer>
<SectionContainer className="py-0!">
<div className="w-full border-b" />
@@ -57,4 +56,41 @@ const OpenSource = () => {
)
}
async function fetchSupabaseRepos(): Promise<GitHubRepo[] | null> {
try {
const res = await fetch('https://api.github.com/orgs/supabase/repos?type=public&per_page=100', {
headers: { Accept: 'application/vnd.github+json' },
signal: AbortSignal.timeout(10_000),
})
if (!res.ok) throw new Error(`GitHub responded ${res.status}`)
const data: unknown = await res.json()
if (!Array.isArray(data)) throw new Error('GitHub returned a non-array body')
const tabRepoNames = new Set(pageData.repo_tabs.flatMap((tab) => tab.repos ?? []))
return data
.filter((repo) => tabRepoNames.has(repo.name))
.map((repo) => ({
name: repo.name,
description: repo.description ?? null,
html_url: repo.html_url,
full_name: repo.full_name,
forks: repo.forks ?? 0,
stargazers_count: repo.stargazers_count ?? 0,
}))
} catch (error) {
console.error('Failed to fetch supabase repos for /open-source', error)
return null
}
}
export const getStaticProps: GetStaticProps<{ repos: GitHubRepo[] | null }> = async () => {
const repos = await fetchSupabaseRepos()
return {
props: { repos },
revalidate: repos ? 3600 : 60,
}
}
export default OpenSource