// Spiceflow RSC app on Cloudflare Workers with KV. // Custom Worker default exports can still call `app.handle(request)` directly. import './globals.css' import { Spiceflow } from 'spiceflow' import { Suspense } from 'react' import { Link, ProgressBar } from 'spiceflow/react' import { env } from 'cloudflare:workers' import { isTruthy } from 'spiceflow/src/utils' type Pokemon = { id: number name: string type: string } export const app = new Spiceflow() // Runs for every request, prerendered staticPage routes included. .use(async ({ request, redirect }, next) => { if (new URL(request.url).pathname === '/about-us') throw redirect('/about') const response = await next() response.headers.set('x-middleware', 'spiceflow') return response }) .layout('/*', async ({ children }) => { return ( }>{children} ) }) .page('/', async function Home() { const kv = env.POKEMON_KV const allIds: number[] = JSON.parse((await kv.get('__ids')) || '[]') // Pick 12 random IDs const shuffled = allIds.sort(() => Math.random() - 0.5).slice(0, 12) const pokemon = (await Promise.all( shuffled.map((id) => kv.get(`pokemon:${id}`, 'json')), )).filter(isTruthy) return ( {pokemon.map((p) => ( ))} ) }) // Prerendered at build time. The Worker serves the stored files after the middleware above. .staticPage('/about', async function About() { return (

Static about page, prerendered at build time.

Back to list
) }) .staticGet('/build-info.json', () => Response.json({ builtAt: new Date().toISOString() }), ) .layout('/pokemon/:id', ({ children }) => { return (
Loading...
}>{children} ) }) .page('/pokemon/:id', async function PokemonDetails({ params: { id } }) { const kv = env.POKEMON_KV const pokemon = await kv.get(`pokemon:${Number(id)}`, 'json') if (!pokemon) { return
Pokemon not found
} return (
Back to list
) }) function Loading() { return ( ) } function PokemonList({ children }: { children: React.ReactNode }) { return ( ) } function PokemonCard({ id, name }: { id: number; name: string }) { return (
  • {name} {name}
  • ) } function RootLayout({ children }: { children: React.ReactNode }) { return ( How is this not illegal? (Cloudflare KV edition)

    How is this not illegal?

    This page reads{' '} POKEMON_KV {' '} from Cloudflare Workers KV, for every request.

    Data fetching is defined directly within the component tree thanks to React Server Components.

    {children}
    ) } declare module 'spiceflow/react' { interface SpiceflowRegister { app: typeof app } } export { MyDurableObject } from './durable-object' export default { async fetch(request: Request) { return app.handle(request) }, }