Structuring your Project
Determining how to structure web app when building on Cloudflare Workers can often feel paralyzing, especially if you're migrating an existing codebase.
It's recommended that you conceptualize your app as if it were three separate codebases in a single Git repo:
- The server bundle, executed by Cloudflare's Worker runtime
- The browser bundle, executed within the user's browser
- And the shared code consumed by both bundles
Directory structure
Keywork provides a batteries-included example repo to help spending too much of your time implementing this project structure.
This project uses ESBuild to bundle your code from three separate package directories...
Worker
/packages/worker
The complete and bundled Worker code to be uploaded to Cloudflare Pages. This includes your routing logic, data fetching, React components, and server-side rendering.
A worker only supports a single JavaScript file, so if we want to split our code into separate files, or import modules from NPM, we’ll need a build step that bundles all of our code. For this we use ESBuild.
Because Keywork apps automatically handle routing, ESBuild has been configured to output a _worker.js
file,
automatically configuring Cloudflare Pages to disable the functions directory and enable advanced mode.
This package can import from...
- NPM packages declared in
/packages/worker/package.json
@packages/shared
Browser
/packages/browser
The client-side bundle to be served statically by your Worker, and interpreted by the browser. This includes your React components, client-side hydration.
This package can import from...
- NPM packages declared in
/packages/browser/package.json
@packages/shared
Shared
/packages/shared
While this isn't a separate bundle per se, both the worker
and browser
bundles will import
shared modules such as your React components and other shared utilities.
This package can import from...
- NPM packages declared in
/packages/shared/package.json
@packages/shared
Distribution
dist
The contents of this directory will be generated by ESBuild and uploaded to Cloudflare Pages and served as your site's static content.
Bundled Worker
_worker.js
The bundled code that will be generated by ESBuild. This comprises the entirety of your deployed worker.