Virtual Modules
As covered in Project Structure, @fastify/react
relies on virtual modules to save your project from having too many boilerplate files. Virtual modules used in @fastify/react
are fully ejectable. For instance, the starter template relies on the $app/root.jsx
virtual module to provide the React component shell of your application. If you copy the root.jsx
file from the @fastify/react package and place it your Vite project root, that copy of the file is used instead.
$app/root.jsx
This is the root React component. It's used internally by $app/create.jsx
and provided as part of the starter template. You can use this file to add a common layout to all routes, or just use it to add additional, custom context providers.
Note that a top-level <Suspense>
wrapper is necessary because @fastify/react
has code-splitting enabled at the route-level. You can opt out of code-splitting by providing your own routes.js
file, but that's very unlikely to be ever required for any reason.
Source from packages/fastify-react/virtual/root.jsx
:
import { Suspense } from 'react'
import { Route, Routes } from 'react-router'
import { AppRoute, Router } from '$app/core.jsx'
export default function Root({ url, routes, head, ctxHydration, routeMap }) {
return (
<Suspense>
<Router location={url}>
<Routes>
{routes.map(({ path, component: Component }) => (
<Route
key={path}
path={path}
element={
<AppRoute
head={head}
ctxHydration={ctxHydration}
ctx={routeMap[path]}
>
<Component />
</AppRoute>
}
/>
))}
</Routes>
</Router>
</Suspense>
)
}
import { Suspense } from 'react'
import { Route, Routes } from 'react-router'
import { AppRoute, Router } from '$app/core.jsx'
export default function Root({ url, routes, head, ctxHydration, routeMap }) {
return (
<Suspense>
<Router location={url}>
<Routes>
{routes.map(({ path, component: Component }) => (
<Route
key={path}
path={path}
element={
<AppRoute
head={head}
ctxHydration={ctxHydration}
ctx={routeMap[path]}
>
<Component />
</AppRoute>
}
/>
))}
</Routes>
</Router>
</Suspense>
)
}
$app/routes.js
@fastify/react
has code-splitting out of the box. It does that by eagerly loading all route data on the server, and then hydrating any missing metadata on the client. That's why the routes module default export is conditioned to i
, and different helper functions are called for each rendering environment.
React Router's nested routes aren't supported yet.
Source from packages/fastify-react/virtual/routes.js
:
export default import.meta.glob('/pages/**/*.{jsx,tsx}')
export default import.meta.glob('/pages/**/*.{jsx,tsx}')
$app/core.jsx
Implements useRouteContext()
, App
and AppRoute
.
App
is imported by root.jsx
and encapsulates @fastify/react
's route component API.
Source from packages/fastify-react/virtual/core.jsx
:
import { createPath } from 'history'
import { useEffect } from 'react'
import { BrowserRouter, StaticRouter, useLocation } from 'react-router'
import { proxy } from 'valtio'
import { RouteContext, useRouteContext } from '@fastify/react/client'
import layouts from '$app/layouts.js'
import { waitFetch, waitResource } from '$app/resource.js'
export const isServer = import.meta.env.SSR
export const Router = isServer ? StaticRouter : BrowserRouter
let serverActionCounter = 0
export function createServerAction(name) {
return `/-/action/${name ?? serverActionCounter++}`
}
export function useServerAction(action, options = {}) {
if (import.meta.env.SSR) {
const { req, server } = useRouteContext()
req.route.actionData[action] = waitFetch(
`${server.serverURL}${action}`,
options,
req.fetchMap,
)
return req.route.actionData[action]
}
const { actionData } = useRouteContext()
if (actionData[action]) {
return actionData[action]
}
actionData[action] = waitFetch(action, options)
return actionData[action]
}
export function AppRoute({ head, ctxHydration, ctx, children }) {
// If running on the server, assume all data
// functions have already ran through the preHandler hook
if (isServer) {
const Layout = layouts[ctxHydration.layout ?? 'default']
return (
<RouteContext.Provider
value={{
...ctx,
...ctxHydration,
state: isServer
? ctxHydration.state ?? {}
: proxy(ctxHydration.state ?? {}),
}}
>
<Layout>{children}</Layout>
</RouteContext.Provider>
)
}
// Note that on the client, window.route === ctxHydration
// Indicates whether or not this is a first render on the client
ctx.firstRender = window.route.firstRender
// If running on the client, the server context data
// is still available, hydrated from window.route
if (ctx.firstRender) {
ctx.data = window.route.data
ctx.head = window.route.head
} else {
ctx.data = undefined
ctx.head = undefined
}
const location = useLocation()
const path = createPath(location)
// When the next route renders client-side,
// force it to execute all URMA hooks again
// biome-ignore lint/correctness/useExhaustiveDependencies: I'm inclined to believe you, Biome, but I'm not risking it.
useEffect(() => {
window.route.firstRender = false
window.route.actionData = {}
}, [location])
// If we have a getData function registered for this route
if (!ctx.data && ctx.getData) {
try {
const { pathname, search } = location
// If not, fetch data from the JSON endpoint
ctx.data = waitFetch(`/-/data${pathname}${search}`)
} catch (status) {
// If it's an actual error...
if (status instanceof Error) {
ctx.error = status
}
// If it's just a promise (suspended state)
throw status
}
}
// Note that ctx.loader() at this point will resolve the
// memoized module, so there's barely any overhead
if (!ctx.firstRender && ctx.getMeta) {
const updateMeta = async () => {
const { getMeta } = await ctx.loader()
head.update(await getMeta(ctx))
}
waitResource(path, 'updateMeta', updateMeta)
}
if (!ctx.firstRender && ctx.onEnter) {
const runOnEnter = async () => {
const { onEnter } = await ctx.loader()
const updatedData = await onEnter(ctx)
if (!ctx.data) {
ctx.data = {}
}
Object.assign(ctx.data, updatedData)
}
waitResource(path, 'onEnter', runOnEnter)
}
const Layout = layouts[ctx.layout ?? 'default']
return (
<RouteContext.Provider
value={{
...ctxHydration,
...ctx,
state: isServer
? ctxHydration.state ?? {}
: proxy(ctxHydration.state ?? {}),
}}
>
<Layout>{children}</Layout>
</RouteContext.Provider>
)
}
import { createPath } from 'history'
import { useEffect } from 'react'
import { BrowserRouter, StaticRouter, useLocation } from 'react-router'
import { proxy } from 'valtio'
import { RouteContext, useRouteContext } from '@fastify/react/client'
import layouts from '$app/layouts.js'
import { waitFetch, waitResource } from '$app/resource.js'
export const isServer = import.meta.env.SSR
export const Router = isServer ? StaticRouter : BrowserRouter
let serverActionCounter = 0
export function createServerAction(name) {
return `/-/action/${name ?? serverActionCounter++}`
}
export function useServerAction(action, options = {}) {
if (import.meta.env.SSR) {
const { req, server } = useRouteContext()
req.route.actionData[action] = waitFetch(
`${server.serverURL}${action}`,
options,
req.fetchMap,
)
return req.route.actionData[action]
}
const { actionData } = useRouteContext()
if (actionData[action]) {
return actionData[action]
}
actionData[action] = waitFetch(action, options)
return actionData[action]
}
export function AppRoute({ head, ctxHydration, ctx, children }) {
// If running on the server, assume all data
// functions have already ran through the preHandler hook
if (isServer) {
const Layout = layouts[ctxHydration.layout ?? 'default']
return (
<RouteContext.Provider
value={{
...ctx,
...ctxHydration,
state: isServer
? ctxHydration.state ?? {}
: proxy(ctxHydration.state ?? {}),
}}
>
<Layout>{children}</Layout>
</RouteContext.Provider>
)
}
// Note that on the client, window.route === ctxHydration
// Indicates whether or not this is a first render on the client
ctx.firstRender = window.route.firstRender
// If running on the client, the server context data
// is still available, hydrated from window.route
if (ctx.firstRender) {
ctx.data = window.route.data
ctx.head = window.route.head
} else {
ctx.data = undefined
ctx.head = undefined
}
const location = useLocation()
const path = createPath(location)
// When the next route renders client-side,
// force it to execute all URMA hooks again
// biome-ignore lint/correctness/useExhaustiveDependencies: I'm inclined to believe you, Biome, but I'm not risking it.
useEffect(() => {
window.route.firstRender = false
window.route.actionData = {}
}, [location])
// If we have a getData function registered for this route
if (!ctx.data && ctx.getData) {
try {
const { pathname, search } = location
// If not, fetch data from the JSON endpoint
ctx.data = waitFetch(`/-/data${pathname}${search}`)
} catch (status) {
// If it's an actual error...
if (status instanceof Error) {
ctx.error = status
}
// If it's just a promise (suspended state)
throw status
}
}
// Note that ctx.loader() at this point will resolve the
// memoized module, so there's barely any overhead
if (!ctx.firstRender && ctx.getMeta) {
const updateMeta = async () => {
const { getMeta } = await ctx.loader()
head.update(await getMeta(ctx))
}
waitResource(path, 'updateMeta', updateMeta)
}
if (!ctx.firstRender && ctx.onEnter) {
const runOnEnter = async () => {
const { onEnter } = await ctx.loader()
const updatedData = await onEnter(ctx)
if (!ctx.data) {
ctx.data = {}
}
Object.assign(ctx.data, updatedData)
}
waitResource(path, 'onEnter', runOnEnter)
}
const Layout = layouts[ctx.layout ?? 'default']
return (
<RouteContext.Provider
value={{
...ctxHydration,
...ctx,
state: isServer
? ctxHydration.state ?? {}
: proxy(ctxHydration.state ?? {}),
}}
>
<Layout>{children}</Layout>
</RouteContext.Provider>
)
}
$app/create.jsx
This virtual module creates your root React component.
This is where root.jsx
is imported.
Source from packages/fastify-react/virtual/create.jsx
:
import Root from '$app/root.jsx'
export default function create({ url, ...serverInit }) {
return <Root url={url} {...serverInit} />
}
import Root from '$app/root.jsx'
export default function create({ url, ...serverInit }) {
return <Root url={url} {...serverInit} />
}
$app/layouts/default.js
This is used internally by $app/core.jsx
. If a project has no layouts/default.jsx
file, the default one from @fastify/react
is used.
Source from packages/fastify-react/virtual/layouts/default.jsx
:
// This file serves as a placeholder
// if no layouts/default.jsx file is provided
import { Suspense } from 'react'
export default function Layout({ children }) {
return <Suspense>{children}</Suspense>
}
// This file serves as a placeholder
// if no layouts/default.jsx file is provided
import { Suspense } from 'react'
export default function Layout({ children }) {
return <Suspense>{children}</Suspense>
}
$app/mount.js
This is the file index.html
links to by default. It sets up the application with an unihead
instance for head management, the initial route context, and provides the conditional mounting logic to defer to CSR-only if clientOnly
is enabled.
Note that this module needs to be referenced as /$app/mount.js
in index.html
.
Source from packages/fastify-react/virtual/mount.js
:
import { createRoot, hydrateRoot } from 'react-dom/client'
import Head from 'unihead/client'
import { hydrateRoutes } from '@fastify/react/client'
import routes from '$app/routes.js'
import create from '$app/create.jsx'
import * as context from '$app/context.js'
async function mountApp (...targets) {
const ctxHydration = await extendContext(window.route, context)
const head = new Head(window.route.head, window.document)
const resolvedRoutes = await hydrateRoutes(routes)
const routeMap = Object.fromEntries(
resolvedRoutes.map((route) => [route.path, route]),
)
const app = create({
head,
ctxHydration,
routes: window.routes,
routeMap,
})
let mountTargetFound = false
for (const target of targets) {
const targetElem = document.querySelector(target)
if (targetElem) {
mountTargetFound = true
if (ctxHydration.clientOnly) {
createRoot(targetElem).render(app)
} else {
hydrateRoot(targetElem, app)
}
break
}
}
if (!mountTargetFound) {
throw new Error(`No mount element found from provided list of targets: ${targets}`)
}
}
mountApp('#root', 'main')
async function extendContext (ctx, {
// The route context initialization function
default: setter,
// We destructure state here just to discard it from extra
state,
// Other named exports from context.js
...extra
}) {
Object.assign(ctx, extra)
if (setter) {
await setter(ctx)
}
return ctx
}
import { createRoot, hydrateRoot } from 'react-dom/client'
import Head from 'unihead/client'
import { hydrateRoutes } from '@fastify/react/client'
import routes from '$app/routes.js'
import create from '$app/create.jsx'
import * as context from '$app/context.js'
async function mountApp (...targets) {
const ctxHydration = await extendContext(window.route, context)
const head = new Head(window.route.head, window.document)
const resolvedRoutes = await hydrateRoutes(routes)
const routeMap = Object.fromEntries(
resolvedRoutes.map((route) => [route.path, route]),
)
const app = create({
head,
ctxHydration,
routes: window.routes,
routeMap,
})
let mountTargetFound = false
for (const target of targets) {
const targetElem = document.querySelector(target)
if (targetElem) {
mountTargetFound = true
if (ctxHydration.clientOnly) {
createRoot(targetElem).render(app)
} else {
hydrateRoot(targetElem, app)
}
break
}
}
if (!mountTargetFound) {
throw new Error(`No mount element found from provided list of targets: ${targets}`)
}
}
mountApp('#root', 'main')
async function extendContext (ctx, {
// The route context initialization function
default: setter,
// We destructure state here just to discard it from extra
state,
// Other named exports from context.js
...extra
}) {
Object.assign(ctx, extra)
if (setter) {
await setter(ctx)
}
return ctx
}
$app/resource.js
Provides the waitResource()
and waitFetch()
data fetching helpers implementing the Suspense API. They're used by $app/core.jsx
.
Source from packages/fastify-react/virtual/resource.js
:
const clientFetchMap = new Map()
const clientResourceMap = new Map()
export function waitResource(
path,
id,
promise,
resourceMap = clientResourceMap,
) {
const resourceId = `${path}:${id}`
const loaderStatus = resourceMap.get(resourceId)
if (loaderStatus) {
if (loaderStatus.error) {
throw loaderStatus.error
}
if (loaderStatus.suspended) {
throw loaderStatus.promise
}
resourceMap.delete(resourceId)
return loaderStatus.result
}
const loader = {
suspended: true,
error: null,
result: null,
promise: null,
}
loader.promise = promise()
.then((result) => {
loader.result = result
})
.catch((loaderError) => {
loader.error = loaderError
})
.finally(() => {
loader.suspended = false
})
resourceMap.set(resourceId, loader)
return waitResource(path, id)
}
export function waitFetch(path, options = {}, fetchMap = clientFetchMap) {
const loaderStatus = fetchMap.get(path)
if (loaderStatus) {
if (loaderStatus.error || loaderStatus.data?.statusCode === 500) {
if (loaderStatus.data?.statusCode === 500) {
throw new Error(loaderStatus.data.message)
}
throw loaderStatus.error
}
if (loaderStatus.suspended) {
throw loaderStatus.promise
}
fetchMap.delete(path)
return loaderStatus.data
}
const loader = {
suspended: true,
error: null,
data: null,
promise: null,
}
loader.promise = fetch(path, options)
.then((response) => response.json())
.then((loaderData) => {
loader.data = loaderData
})
.catch((loaderError) => {
loader.error = loaderError
})
.finally(() => {
loader.suspended = false
})
fetchMap.set(path, loader)
return waitFetch(path, options, fetchMap)
}
const clientFetchMap = new Map()
const clientResourceMap = new Map()
export function waitResource(
path,
id,
promise,
resourceMap = clientResourceMap,
) {
const resourceId = `${path}:${id}`
const loaderStatus = resourceMap.get(resourceId)
if (loaderStatus) {
if (loaderStatus.error) {
throw loaderStatus.error
}
if (loaderStatus.suspended) {
throw loaderStatus.promise
}
resourceMap.delete(resourceId)
return loaderStatus.result
}
const loader = {
suspended: true,
error: null,
result: null,
promise: null,
}
loader.promise = promise()
.then((result) => {
loader.result = result
})
.catch((loaderError) => {
loader.error = loaderError
})
.finally(() => {
loader.suspended = false
})
resourceMap.set(resourceId, loader)
return waitResource(path, id)
}
export function waitFetch(path, options = {}, fetchMap = clientFetchMap) {
const loaderStatus = fetchMap.get(path)
if (loaderStatus) {
if (loaderStatus.error || loaderStatus.data?.statusCode === 500) {
if (loaderStatus.data?.statusCode === 500) {
throw new Error(loaderStatus.data.message)
}
throw loaderStatus.error
}
if (loaderStatus.suspended) {
throw loaderStatus.promise
}
fetchMap.delete(path)
return loaderStatus.data
}
const loader = {
suspended: true,
error: null,
data: null,
promise: null,
}
loader.promise = fetch(path, options)
.then((response) => response.json())
.then((loaderData) => {
loader.data = loaderData
})
.catch((loaderError) => {
loader.error = loaderError
})
.finally(() => {
loader.suspended = false
})
fetchMap.set(path, loader)
return waitFetch(path, options, fetchMap)
}