Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 24 additions & 32 deletions server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import * as _schemas from '~/api/schemas'
import * as _uploads from '~/api/uploads'
import * as _versions from '~/api/versions'
import { auth } from '~/lib/auth'
import { getSessionUser } from '~/lib/auth.server'
import { getMirrorConfig } from '~/lib/mirror-config'

const isProd = process.env.NODE_ENV === 'production'
Expand Down Expand Up @@ -230,6 +231,18 @@ app.get('/api/blog/:slug', (c) => {
return c.html(typeof html === 'string' ? html : '')
})

// --- App context (consumed by root loader) ---
app.get('/api/context', async (c) => {
const user = await getSessionUser(c.req.raw)
const config = getMirrorConfig()
return c.json({
currentUser: user,
mirrorConfig: config,
kfAccountUrl: process.env.OIDC_ACCOUNT_URL ?? 'http://localhost:3001',
kfAuthUrl: process.env.OIDC_ISSUER_URL ?? 'http://localhost:3000',
})
})

// API 404 catch-all
app.all('/api/*', (c) => {
return c.json({ error: 'API route not found', statusCode: 404 }, 404)
Expand All @@ -253,30 +266,20 @@ if (isProd) {
await runMigrations()

const template = readFileSync(clientHtml, 'utf-8')
const { render, loadData } = await import(ssrBundle as string)

app.get('/__data', async (c) => {
const path = new URL(c.req.url).searchParams.get('path')
if (!path) return c.json({ error: 'Missing path param' }, 400)
const fakeUrl = new URL(path, c.req.url)
const req = new Request(fakeUrl, { headers: c.req.raw.headers })
const result = await loadData(req)
if (result.redirect) return c.json({ redirect: result.redirect }, 200)
return c.json(result)
})
const { render } = await import(ssrBundle as string)

app.get('*', async (c) => {
const { html, ssrData, redirect, statusCode, title, description } = await render(c.req.raw)
const { html, hydrationData, redirect, statusCode, title, description } = await render(
c.req.raw,
)

if (redirect) {
return c.redirect(redirect, 302)
}
if (redirect) return c.redirect(redirect, statusCode ?? 302)

let page = template
.replace('<!--ssr-outlet-->', html)
.replace(
'<!--ssr-data-->',
`<script>window.__SSR_DATA__=${JSON.stringify(ssrData).replace(/</g, '\\u003c')}</script>`,
`<script>window.__staticRouterHydrationData=${hydrationData}</script>`,
)

if (title) {
Expand Down Expand Up @@ -309,34 +312,23 @@ if (isProd) {
})
})

app.get('/__data', async (c) => {
const path = new URL(c.req.url).searchParams.get('path')
if (!path) return c.json({ error: 'Missing path param' }, 400)
const { loadData } = await vite!.ssrLoadModule('/src/entry-server.tsx')
const fakeUrl = new URL(path, c.req.url)
const req = new Request(fakeUrl, { headers: c.req.raw.headers })
const result = await loadData(req)
if (result.redirect) return c.json({ redirect: result.redirect }, 200)
return c.json(result)
})

app.get('*', async (c) => {
const url = c.req.url
let template = readFileSync(resolve('index.html'), 'utf-8')
template = await vite!.transformIndexHtml(url, template)

const { render } = await vite!.ssrLoadModule('/src/entry-server.tsx')
const { html, ssrData, redirect, statusCode, title, description } = await render(c.req.raw)
const { html, hydrationData, redirect, statusCode, title, description } = await render(
c.req.raw,
)

if (redirect) {
return c.redirect(redirect, 302)
}
if (redirect) return c.redirect(redirect, statusCode ?? 302)

let page = template
.replace('<!--ssr-outlet-->', html)
.replace(
'<!--ssr-data-->',
`<script>window.__SSR_DATA__=${JSON.stringify(ssrData).replace(/</g, '\\u003c')}</script>`,
`<script>window.__staticRouterHydrationData=${hydrationData}</script>`,
)

if (title) {
Expand Down
54 changes: 31 additions & 23 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,35 @@
import { lazy, Suspense } from 'react'
import { Route, Routes } from 'react-router'
import type { LoaderFunctionArgs, RouteObject } from 'react-router'

import { AppErrorBoundary } from '~/components/NotFound'
import { buildRoutes } from '~/route-gen'
import Root from '~/components/Root'
import { buildDataRoutes } from '~/route-gen'

const modules = import.meta.glob<{ default: React.ComponentType }>('./routes/**/[!_]*.tsx')
const routes = buildRoutes(modules)
const components = import.meta.glob<{ default: React.ComponentType }>('./routes/**/[!_]*.tsx')
const dataModules = import.meta.glob<{
loader?: RouteObject['loader']
handle?: unknown
middleware?: RouteObject['middleware']
}>('./routes/**/*.data.ts', { eager: true })

const componentMap = new Map(routes.map((r) => [r.path, lazy(modules[r.filePath]!)]))

export { routes }

export default function App() {
return (
<AppErrorBoundary>
<Suspense>
<Routes>
{routes.map((r) => {
const Page = componentMap.get(r.path)
return Page ? <Route key={r.path} path={r.path} element={<Page />} /> : null
})}
</Routes>
</Suspense>
</AppErrorBoundary>
)
async function rootLoader({ request }: LoaderFunctionArgs) {
const res = await fetch(new URL('/api/context', request.url), {
headers: { Cookie: request.headers.get('Cookie') ?? '' },
})
if (!res.ok) {
return {
currentUser: null,
mirrorConfig: { enabled: false, upstream: '', nodeName: '', syncSchedule: '', apiKey: '' },
kfAccountUrl: '',
kfAuthUrl: '',
}
}
return res.json()
}

export const routes: RouteObject[] = [
{
id: 'root',
Component: Root,
loader: rootLoader,
children: buildDataRoutes(components, dataModules),
},
]
11 changes: 2 additions & 9 deletions src/components/BaseLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import { Link } from 'react-router'

import UserMenu from '~/components/UserMenu'
import { useSSRData } from '~/lib/ssr-data'

interface MirrorConfig {
enabled: boolean
nodeName: string
upstream: string
}
import { useAppContext } from '~/lib/app-context'

export default function BaseLayout({ children }: { children: React.ReactNode }) {
const currentUser = useSSRData<any>('currentUser')
const mirrorConfig = useSSRData<MirrorConfig>('mirrorConfig')
const { currentUser, mirrorConfig } = useAppContext()

return (
<>
Expand Down
36 changes: 36 additions & 0 deletions src/components/Root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Suspense, useEffect } from 'react'
import { Outlet, useMatches } from 'react-router'

import { AppErrorBoundary } from '~/components/NotFound'

function DocumentTitle() {
const matches = useMatches()

useEffect(() => {
for (let i = matches.length - 1; i >= 0; i--) {
const { handle, params, data } = matches[i] as {
handle?: { title?: string | ((p: Record<string, string>, d: unknown) => string) }
params: Record<string, string>
data: unknown
}
if (handle?.title) {
document.title =
typeof handle.title === 'function' ? handle.title(params, data) : handle.title
break
}
}
}, [matches])

return null
}

export default function Root() {
return (
<AppErrorBoundary>
<DocumentTitle />
<Suspense>
<Outlet />
</Suspense>
</AppErrorBoundary>
)
}
31 changes: 19 additions & 12 deletions src/entry-client.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import { hydrateRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router'
import { createBrowserRouter, RouterProvider } from 'react-router'

import App from '~/App'
import { getClientSSRData, SSRDataProvider } from '~/lib/ssr-data'
import { routes } from '~/App'

import '~/global.css'

const ssrData = getClientSSRData()
const router = createBrowserRouter(routes, {
hydrationData: (window as any).__staticRouterHydrationData,
future: { v8_middleware: true },
})

hydrateRoot(
document.getElementById('root')!,
<BrowserRouter>
<SSRDataProvider data={ssrData}>
<App />
</SSRDataProvider>
</BrowserRouter>,
)
// Wait for React.lazy route components to resolve before hydrating
if (!router.state.initialized) {
await new Promise<void>((resolve) => {
const unsub = router.subscribe((state) => {
if (state.initialized) {
unsub()
resolve()
}
})
})
}

hydrateRoot(document.getElementById('root')!, <RouterProvider router={router} />)
98 changes: 58 additions & 40 deletions src/entry-server.tsx
Original file line number Diff line number Diff line change
@@ -1,74 +1,92 @@
import { PassThrough } from 'node:stream'

import { renderToPipeableStream } from 'react-dom/server'
import { StaticRouter } from 'react-router'
import { createStaticHandler, createStaticRouter, StaticRouterProvider } from 'react-router'

import App, { routes } from '~/App'
import { SSRDataProvider } from '~/lib/ssr-data'
import { runLoaders } from '~/loaders.server'
import { matchRoutes } from '~/route-gen'
import { routes } from '~/App'

type LoaderResult = {
data: Record<string, unknown>
redirect?: string
statusCode?: number
title?: string
description?: string
}

export async function loadData(request: Request): Promise<LoaderResult> {
return runLoaders(matchRoutes(routes, request.url), request)
}
const handler = createStaticHandler(routes, { future: { v8_middleware: true } })

export async function render(request: Request): Promise<{
html: string
ssrData: Record<string, unknown>
hydrationData: string
redirect?: string
statusCode?: number
title?: string
description?: string
}> {
const pathname = new URL(request.url, 'http://localhost').pathname
const context = await handler.query(request)

const result = await loadData(request).catch((err: unknown) => {
console.error('Loader error:', err)
return { data: {}, statusCode: 500 } as LoaderResult
})

if (result.redirect) {
if (context instanceof Response) {
return {
html: '',
ssrData: {},
redirect: result.redirect,
statusCode: result.statusCode ?? 302,
hydrationData: '{}',
redirect: context.headers.get('Location') ?? '/',
statusCode: context.status,
}
}

// Extract title from deepest matched route's handle
let title: string | undefined
let description: string | undefined
for (let i = context.matches.length - 1; i >= 0; i--) {
const match = context.matches[i]!
const handle = match.route.handle as
| {
title?: string | ((p: Record<string, string>, d: unknown) => string)
description?: string | ((p: Record<string, string>, d: unknown) => string)
}
| undefined
if (handle?.title && !title) {
title =
typeof handle.title === 'function'
? handle.title(
match.params as Record<string, string>,
context.loaderData[match.route.id!],
)
: handle.title
}
if (handle?.description && !description) {
description =
typeof handle.description === 'function'
? handle.description(
match.params as Record<string, string>,
context.loaderData[match.route.id!],
)
: handle.description
}
if (title && description) break
}

const router = createStaticRouter(handler.dataRoutes, context)

return new Promise((resolve, reject) => {
let html = ''
const passthrough = new PassThrough()
passthrough.on('data', (chunk) => {
passthrough.on('data', (chunk: Buffer) => {
html += chunk.toString()
})

const { pipe } = renderToPipeableStream(
<StaticRouter location={pathname}>
<SSRDataProvider data={result.data}>
<App />
</SSRDataProvider>
</StaticRouter>,
<StaticRouterProvider router={router} context={context} />,
{
onAllReady() {
pipe(passthrough)
passthrough.on('end', () =>
passthrough.on('end', () => {
const hydrationData = JSON.stringify({
loaderData: context.loaderData,
actionData: context.actionData ?? null,
errors: context.errors ?? null,
}).replace(/</g, '\\u003c')

resolve({
html,
ssrData: result.data,
...(result.statusCode !== undefined && { statusCode: result.statusCode }),
...(result.title !== undefined && { title: result.title }),
...(result.description !== undefined && { description: result.description }),
}),
)
hydrationData,
...(context.statusCode !== 200 && { statusCode: context.statusCode }),
...(title !== undefined && { title }),
...(description !== undefined && { description }),
})
})
},
onError: reject,
},
Expand Down
Loading
Loading