Let me tell you the story of how I learned that you can build Progressive Web Apps on Cloudflare’s network around the globe with one JavaScript bundle that runs both in the browser and on Cloudflare Workers with no modification and no separate bundling for client and server. And when registered as a Service Worker, the same JavaScript bundle will turn your page into a Progressive Web App that doesn’t even make network requests. Here's how that works...

"Any resemblance to actual startups, living or IPO'd, is purely coincidental and unintended" - @sevki

A (possibly apocryphal) Story

I recently met up with some old friends in London who told me they were starting a new business. They did what every coder would do... they quickly hacked something together, bought a domain, and registered the GitHub org and thus Buzzwords was born.

The idea was simple: you could feed the name of your application into a machine learning model and it would generate the configuration files for your deployment for various container orchestrators. They achieved this by going through millions of deployment configurations and training a linear regression model by gamifying quantum computing because blockchain, or something (I told you this story was apocryphal).

I was intrigued, to say the least, but I was playing it cool. One of the co-founders broke the silence, "So, does any of these sound like something you'd like to work on?" I struggled with it for tens of seconds. You see I only recently started this new job at Cloudflare, and I actually like my job and the people I work with. So I said, "Hell yeah, man, let's change the world one container at a time". One of them said, "Well, since we really can’t pay you right now, and we don't seem to be able to set aside enough time to build our website, would you mind helping us out with that on a trial basis, like an interview?" I enthusiastically accepted.

So while the Buzzwords crew were busy producing HYPE, I set off to build their website. As any business starting up, discover-ability is paramount to them, so Buzzwords definitely needs to be optimized for search engines so they can generate organic traffic from keywords like "machine learning", "YAML", "containers" and "blockchain".

When parsing dynamic pages, crawlers need to do more work, there is an inherent penalty for using fancy frameworks compared to plain old HTML.

Don’t take my word for it, as Google cautions;

Currently, it's difficult to process JavaScript and not all search engine crawlers are able to process it successfully or immediately. In the future, we hope that this problem can be fixed, but in the meantime, we recommend dynamic rendering as a workaround solution to this problem.

Yet, the Buzzwords folks still wanted something fancy I told them about this new thing called React hooks. I slammed a La Croix and put together the 2018 equivalent of Hello, World! which is still Hello, World! but with an 👋 at the end.

import React from "react"; import ReactDOMServer from "react-dom/server"; class HelloMessage extends React.Component { render() { return <div>Hello, {this.props.name} 👋</div>; } } async function handleRequest(event) { return new Response(ReactDOMServer.renderToString(<HelloMessage name="World" />), { headers: { "Content-Type": "text/html" } }); } self.addEventListener("fetch", event => { event.respondWith(handleRequest(event)); });

Other than setting up Webpack to bundle your code, this is pretty much all you need to get started with React and Cloudflare Workers. But Hello, World! is hardly a startup website. Thankfully, since all startup websites look exactly the same it's really not that hard to build one. First, I mapped the paths to pages:

let routes = { "/": <Home />, "/hype": <Hype />, "/careers": <Careers /> };

Instead of rendering any old component, I just used the URL's pathname , available both in the browser and the edge, to pick the correct component.

const header = `<!DOCTYPE html> <!-- ... -->`; const footer = `</html> <!-- ... -->`; async function handleRequest(event) { const u = new URL(event.request.url); let body = ReactDOMServer.renderToString(React.cloneElement(routes[u.pathname], {name:"World"} )); return new Response(header + body + footer, { headers: { "Content-Type": "text/html" } }); }

But what good is it to use React when you just render HTML and nothing is interactive anymore? Unfortunately, we can’t use React.render to make it interactive again, thankfully React.hydrate allows us to continue rendering applications where they left off at the server, instead of re-rendering everything from scratch.

Going back to Hello, World! if we don't give it the same state, it will not print anything after Hello. So, all I had to do was add these three lines.

if (typeof navigator !== "undefined") { const app = document.querySelector("#app"); ReactDOM.hydrate(React.cloneElement(routes[location.pathname], {name:"World"} ), app); }

One of the co-founders was very quick to pick up on the fact that I was using the same routes table for both rendering and hydrating. "That's because I used the same exact bundle" I explained, "because Cloudflare Workers use the same Web APIs that are available in the browser. There is no need to compile different versions of the same logic and split things into server.js and client.js . fetch is fetch and that's that. No polyfills." I added from my high horse.

They still felt that this wasn’t buzzwordy enough. So I asked them if they've heard of Progressive Web Apps, they stared back with a blank look on their face, I proceeded to explain.

"It's the name given to a set of standard web technologies, which helps you build native-feeling applications using Service Workers, JavaScript and WASM"

"Oh cool! So it's like an Electron app!" one of the co-founders grunted.

"NO! STOP TRYING TO MAKE EVERYTHING BUZZWORDY!" I whispered before I proceeded to explain PWAs are. Progressive Web Apps once installed, gives extra functionality to your app that make it act and feel like a native application. For instance, PWAs can receive notifications, work offline and do work in the background without blocking UI changes. The underlying technology is supported by Microsoft, Google, Apple, Samsung, Mozilla and Cloudflare. Not only that but, any PWA you build on Workers can be submitted to Microsoft's App Store and then installed on a Windows desktop, or added to your phone’s home screen, or a Chrome desktop, and it will then run as a standalone app. I copy and pasted a code snippet from the Google Web Fundamentals Blog to register a Service Worker. (Great thing about sharing APIs is sharing documentation too!)

if (typeof navigator !== "undefined") { // if (pid != 0) window.addEventListener("load", function() { const app = document.querySelector("#app"); ReactDOM.hydrate(React.cloneElement(routes[location.pathname], {name:"World"}), app); if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/worker.js").then( function(registration) { // Registration was successful console.log( "ServiceWorker registration successful with scope: ", registration.scope ); }, function(err) { // registration failed :( console.log("ServiceWorker registration failed: ", err); } ); } }); }

Thus the same code that hijacks fetches on Cloudflare Workers will do so on browsers too using the same exact ReactDOMServer.renderToString function to render the page offline.

async function handleRequest(event) { const u = new URL(event.request.url); if (u.pathname in routes) { let rendered = ReactDOMServer.renderToString(React.cloneElement(routes[u.pathname],{name:"World"})); return new Response(header + rendered + footer, { headers: { "Content-Type": "text/html" } }); } return fetch(event.request); }

Then I pulled up the network tab and reloaded the page:

I continued to explain: every request except for the buzzwords.app request is repeated. That's because a Service Worker basically acts as a proxy, grabbing requests preventing the browser default load behaviour, allowing you to define how a request should be fetched. Since the first thing we have done was to add a call back for the fetch event (both on Cloudflare Workers, and Service Workers) it will call that function for each fetch event. “But wait there's more!”, I should have exclaimed, but I didn't. But they knew what was up, they could tell by how intensely I was staring at the code.

As my pièce de résistance I searched for Cloudflare Workers Cache, and copy and pasted some more code. Which made the handleRequest function look like this:

async function handleRequest(event) { const u = new URL(event.request.url); if (u.pathname in routes) { let rendered = ReactDOMServer.renderToString(React.cloneElement(routes[u.pathname],{name:"World"})); return new Response(header + rendered + footer, { headers: { "Content-Type": "text/html" } }); } let cache = await caches.open("buzz"); let response = await cache.match(event.request); if (!response) { response = await fetch(event.request); event.waitUntil(cache.put(event.request, response.clone())); } return response; }

This code works both on Cloudflare Workers and for Service Workers. If the page requested is not available on the Worker, it will check the cache, if it's not available in the cache, it will fetch it from the origin, making not only the code but also the behaviours truly isomorphic.

I pulled up the network tab again, reloaded the page and showed them all the repeated requests had now disappeared. I then turned off the WiFi and hit reload to show that the application was in fact still working offline.

Folks, this is not HYPE, this is more, using this technique you can build applications that run exactly the same on the server, as they do in the browser. If the browser has support, it will work offline and will not cost you a single dime more when it’s online, if the browser doesn’t support it, or even if JavaScript is disabled, it will still render. And you can take the same application and submit them to Microsoft's App Store, install them as standalone applications on your Android phone or Chromebook. All without having to write a single line more than you would have to build a web page.

All the code from this blog post is available on the Cloudflare GitHub.

If you just want to use React to do static page rendering on Cloudflare Workers you can clone https://github.com/cloudflare/workers-react-example and do cd workers && yarn install && yarn preview to get your page rendering on cloudflareworkers.com instantly

If you want the full Progressive Web App experience you can clone https://github.com/cloudflare/workers-react-pwa-example and set up terraform variables to upload your Worker script to both Cloudflare and a storage bucket to start building your application in a couple of minutes.

Please let us know if you build on this, we'd love to know what you do with it.