Cloudflare Workers

Examples

Cloudflare Pages & wrangler 2

With wrangler v2, we can deploy a Cloudflare Worker (server code) along Cloudflare Pages (static files).

Example:

See also:

Dev Server

We recommend to:

  • For dev, use an Express.js server instead of a worker, for much faster HMR & dev start. (So we skip wrangler / miniflare / Cloudflare Workers altogether while developing our app. We still use wrangler/miniflare to develop the worker code integration.)
  • For production, bundle the worker code with Cloudflare Workers's webpack bundler.

See examples above.

Bundling

By default, we recommend using Cloudflare Workers's webpack bundler because it's the beaten path; using another bundler may cause subtle differences that may cause problems.

That said, we can use any other bundler (esbuild, rollup, ...) to bundle our worker code.

importBuild.js

Cloudflare Workers requires us to bundle our entire worker code into a single file.

For bundlers to be able to discover & bundle the entire dependency tree, we need to use dist/server/importBuild.js.

Example: /examples/cloudflare-workers/worker/ssr.js.

Universal fetch()

When using Node.js for dev and Cloudflare Workers for production, we may need a fetch() function that works in both environments.

But libraries such as node-fetch or cross-fetch usually don't work with Cloudflare Workers.

What we can do is to define a fetch function at pageContext.fetch that works in all environments. The trick is to add a different fetch() implementation to pageContextInit at renderPage(pageContextInit).

Example: /examples/cloudflare-workers#universal-fetch.

esbuild

For a faster build time, you can bundle your worker with esbuild.

It's not possible to run it from the CLI as it needs the plugin @esbuild-plugins/node-modules-polyfill. Create a build script instead:

// build-worker.js

import esbuild from 'esbuild'
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'

esbuild.build({
  // Necessary for a successful build:
  plugins: [NodeModulesPolyfillPlugin()],
  platform: 'browser',
  conditions: ['node'],

  // Other esbuild options...
})

Example: /examples/cloudflare-workers-esbuild.