Next.js has a great feature called “Partial Prerendering” that allows you to prerender the external “shell” of your app, and defer rendering o

Partial Prerendering for Everyone with Cloudflare Workers

submited by
Style Pass
2024-09-23 22:00:02

Next.js has a great feature called “Partial Prerendering” that allows you to prerender the external “shell” of your app, and defer rendering other parts until they are requested by the client. (Vercel refers to as “PPR”. This is not how acronyms work at all, but vercel sure love their TLAs. Would’ve been odd to call it “PP” though.) This article shows you how you can achieve this for any existing server rendered React app, and serve it with a Cloudflare Worker for great performance.

The example app is based on this fantastic example by Guillermo Rauch called “How is this not illegal?” (which itself is based on a tweet by Dan Abramov, lost to the sands of time). It’s a simple app that fetches a random list of pokemon from a database and displays them. With PPR, we first return a skeleton frame, and then IN THE SAME REQUEST, we continue streaming in the rest of the app. The effect is that we get an incredibly fast initial load that something like an edge network provides you, but without sacrificing the performance benefits of rendering your actual app near your data sources.

For our example, we’re going to rewrite this app with plain React and run it on a Cloudflare Worker. But any React Framework could adopt this technique, and you could run it on any stack/provider. As long as you were already using React’s streaming rendering API renderToReadableStream / renderToPipeableStream to actually render your app, you should be able to rewrite it to take advantage of PPR. We’re going to use Cloudflare’s D1 database for our database, but you could use any database/service here. Despite the original example using React Server Components, you’ll see that PPR doesn’t require you to use RSCs, and you can use PPR with any React framework. Of note, we’re using Cloudflare’s “smart placement” on the application to automatically place the app near the database. And while this stack has 2 Workers (one for serving the shell near the user, and one for serving the app near the data source), in the future Cloudflare will let you write the app as a single Worker, and automatically place the “shell” part near the user and the “app” part near the data source (I think so! I’m speculating here).

Leave a Comment