diff --git a/public/workers/prompts/pages-to-workers.txt b/public/workers/prompts/pages-to-workers.txt index 5595f12132d..6f697724a74 100644 --- a/public/workers/prompts/pages-to-workers.txt +++ b/public/workers/prompts/pages-to-workers.txt @@ -1,176 +1,38 @@ -Migrate Cloudflare Pages to Workers using the guide below: +# Migrate this Cloudflare Pages project to Workers -# Cloudflare Pages to Workers Migration Guide +Implement the migration to Workers with Static Assets in this repository. Preserve the application's production-facing contract unless the user approves a change: public routes, redirects, methods, status codes, meaningful content, and security and cache behavior. Do not treat local emulator output or legacy adapter internals as the contract. Stop after local verification: do not deploy, upload a Preview, change dashboard settings or domains, or disable Pages without permission. -## Goal +Use the project's package manager and lockfile. Keep a supported, compatible Wrangler version; install or upgrade it only if the selected migration needs it. Avoid unrelated framework or dependency upgrades. Use the current [Pages migration guide](https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/) and the [Workers framework guides](https://developers.cloudflare.com/workers/framework-guides/) where applicable. -Migrate a Cloudflare Pages project to Cloudflare Workers with static assets support. +## 1. Establish the Pages baseline -## Core Migration Concepts +- Find the project root, build and deploy commands, Wrangler config, framework and adapter versions, and Pages build output directory. Inspect CI and any available Pages settings for differences between local, production, and preview builds. Do not assume settings absent from the repository are unused. +- Run the existing build before changing it. Inspect the built output for `_worker.js` (file or directory), `_routes.json` (checked in or generated), `_headers`, `_redirects`, and `404.html`. Inspect `functions/` and its middleware. In Pages advanced mode, `_worker.js` takes precedence over `functions/`; do not start running previously inactive Functions. +- Run `wrangler pages dev` locally if possible. Record representative responses: a static asset, a deep link and missing URL, SSR or API endpoints, and any redirects or custom headers. Use the app's routes, tests, configuration, and any available hosted observations to distinguish public behavior from local or adapter artifacts. If an asset and a function share a URL, record which wins. For file-based Functions without a custom `_routes.json`, also inspect the routes Pages generates for deployment: the Functions build supports `--output-routes-path` alongside `--outdir`. Local Pages dev alone does not establish the deployed invocation scope. If you cannot collect a baseline, state what you could not verify and proceed without guessing. -### Understanding the Migration +## 2. Choose the migration path from the build output -When migrating from Pages to Workers, you're essentially: +Do not run `wrangler setup` against an existing Pages config with `pages_build_output_dir`. Without a detected framework, a `functions/` directory also blocks setup. Keep the Pages config as a rollback copy; use the framework's published Workers instructions or migrate file-based Functions manually. -1. Moving from Pages deployment commands to Workers deployment commands -2. Converting Pages-specific configuration to Workers format -3. Handling static assets using Workers Assets (not the deprecated Workers Sites) -4. Converting any Pages Functions to Workers format if they exist +- **Static or client-rendered:** If there is no server code, use an assets-only Worker. A client-side framework or Vite alone does not require a Worker entrypoint, adapter, or `@cloudflare/vite-plugin`. Point `assets.directory` at the built output and omit `main` and `assets.binding`. +- **Framework SSR or APIs:** Follow the Workers path for the installed framework and adapter versions. Keep the adapter if it already supports Workers. Replace a Pages-only adapter or preset where needed, such as `@cloudflare/next-on-pages` or Nitro's `cloudflare_pages`. For Next.js, check the [current Workers framework guide](https://developers.cloudflare.com/workers/framework-guides/web-apps/nextjs/) and compatibility with the app's routes and runtime features before selecting a replacement. Do not treat wrapping a deprecated Pages adapter's output as a completed migration. Use the supported adapter's entrypoint. Add a route-scoped shim only for a demonstrated public behavior gap. Do not recreate legacy diagnostic headers, generated file aliases, or framework internals based only on local observations. Check that Pages build variables such as `CF_PAGES` do not force the adapter back to Pages. Rebuild and inspect the actual Worker entrypoint and assets directory. If the framework generates Wrangler config (for example, Nitro's `cloudflare_module` with `deployConfig` enabled), inspect `.wrangler/deploy/config.json` and its target. Edit the source config or adapter options, not the generated config, and do not pass `--config` to bypass the generated config unintentionally. +- **Advanced mode (`_worker.js`):** Use the built file or the entry file inside the directory (typically `_worker.js/index.js`) as `main`, unless the framework configures it. Keep sibling chunks and modules available to Wrangler. If the handler calls `env.ASSETS`, set `assets.binding` to `ASSETS` unless the adapter already does. Keep the entire server bundle outside `assets.directory`, or exclude its file or directory from assets on every build. +- **File-based Pages Functions:** Preserve the existing handlers and middleware. To keep them during the migration, run `wrangler pages functions build --outdir ./.wrangler/pages-functions` in the project build, outside `assets.directory`, and point `main` at the generated `index.js` or a wrapper around it. Pass the original `--compatibility-date` and any `--compatibility-flags` explicitly; this standalone command does not read Workers config. If the Functions use `assets:` imports, also pass `--build-output-directory` pointing to the final asset output. Configure `assets.binding` as `ASSETS` for the compiled Worker's asset fallback. Do not rewrite the application just to change deployment targets. -### Key Principles +## 3. Preserve configuration and routing -- **Deployment**: Use `wrangler deploy`, never `wrangler pages deploy` -- **Configuration**: Prefer wrangler.jsonc for better documentation support -- **Assets**: Use the modern Workers Assets format: `"assets": {"directory": "path"}` -- **Flexibility**: Adapt the migration to your specific project structure -- **Package Manager**: Use the appropriate package manager for the project (check for bun.lock, bun.lockb, pnpm-lock.yaml, yarn.lock, or package-lock.json) +- Replace `pages_build_output_dir` with Workers Static Assets configuration, or let the framework emit it. Keep one authoritative source Wrangler config, in the existing format when possible. Preserve the existing compatibility date, flags, and applicable settings. If no date was set, check the Pages runtime settings before choosing one for server code. An assets-only project with no previous date can use today's date. +- Choose fallback behavior from the baseline, not the framework name. For a Pages-style `index.html` fallback, use `assets.not_found_handling: "single-page-application"`, even on a multi-page site that relied on it. For a static custom 404, use `"404-page"`. Do not let asset fallbacks replace framework SSR or API responses. Check status, `Location`, and query strings for canonical HTML redirects (such as `.html` and trailing-slash URLs). Workers may return `307` where Pages returned `308`. If the status must stay the same, use an explicit `_redirects` rule only if it also preserves method behavior: it can redirect `POST` where Pages returned `405`. If the redirect must be limited to `GET` and `HEAD`, handle it in a route-scoped Worker and let other methods follow the normal handler or asset path. +- Preserve when Pages invoked the handler before assets, including collisions without middleware or a user-authored `_routes.json`. Use the effective Pages include and exclude rules, including generated rules where applicable. Use `assets.run_worker_first: true` if all requests must run the Worker first. In an array, a matching `!` rule sends requests directly to assets, even on a miss. An asset miss matching neither a positive nor a negative rule can still reach the Worker. Pages `/api/*` also matches `/api`; add the bare path explicitly for includes and excludes when translating a splat. Test both trailing-slash forms. If an array cannot preserve strict handler scope, check excludes before includes in a Worker wrapper. Call the legacy handler only for included paths and return `env.ASSETS.fetch(request)` otherwise. Use `run_worker_first: true` with that guard if necessary, but note that it also invokes the Worker for asset requests. Verify asset hits and misses. +- Keep `_headers` and `_redirects` in the final assets output. Compare headers even if the project has no `_headers`: Pages adds defaults such as `Access-Control-Allow-Origin`, `Referrer-Policy`, and `X-Content-Type-Options` when serving assets. Restore needed defaults only on confirmed static asset or prerendered responses, including intentional overrides and removals. Identify those responses from the asset handler, route source, or build output, not from status or `Content-Type` alone. When restoring static defaults in a wrapper, pass dynamic responses (including errors) and any response marked `private` or `no-store` through unchanged. Do not remove `Vary` values or replace a restricted origin with `*`. Set required headers on Worker-generated responses explicitly, including redirects you recreate. +- Verify that generated server code, its source maps, and files Pages previously ignored (such as `_routes.json`, `functions`, `.wrangler`, `node_modules`, `.git`, or `.DS_Store`) are not public. Remove them from the asset output or generate root `.assetsignore` entries. Make exclusions in build inputs or in a build step, not by hand in generated output. +- Carry over each runtime binding and variable with the same name and intended resource. Map Pages production and preview separately. For branch previews, set an explicit top-level `previews` block in the Wrangler config (empty if no separate settings are needed), not `env.preview`. Follow [Worker Previews configuration](https://developers.cloudflare.com/workers/previews/configuration/) for settings that stay at the top level, and point Preview bindings at test resources rather than production resources. Record dashboard-only settings that still need confirmation. Keep build-time variables separate from runtime ones. Report only secret names, never values; do not copy or commit secrets. -## Migration Steps +## 4. Wire up and verify the migration -### 1. Prerequisites - -- Update Wrangler to version 4 or later using your package manager: - - npm: `npm install --save-dev wrangler@^4.0.0` - - pnpm: `pnpm add --save-dev wrangler@^4.0.0` - - yarn: `yarn add --dev wrangler@^4.0.0` - - bun: `bun add --dev wrangler@^4.0.0` - - This is required as Workers deployment commands have evolved significantly in v4 - - Check current version with `npx wrangler --version` -- Install project dependencies if not already installed -- Consult the official Cloudflare documentation for the latest guidance - -### 2. Configuration Migration - -#### Update Wrangler Configuration - -- Convert to wrangler.jsonc format if using .toml or .json -- Replace `pages_build_output_dir` with `"assets": {"directory": "path"}` -- Ensure a `compatibility_date` field exists - -#### Example Structure - -```jsonc -{ - "name": "project-name", - "compatibility_date": "2025-06-05", - "assets": { "directory": "./dist" }, - // Add other fields as needed -} -``` - -### 3. Determine Project Type - -**First, check for Pages Functions:** - -- Look for a `functions/` directory with .js/.ts files -- If found, you **must** add `wrangler pages functions build` to your build process (see step 6) - -**Then, run your build command and check the output directory:** - -- **If \_worker.js exists**: You have a Workers script project - - Add `"main": "./path/to/_worker.js"` - - Add binding to assets: `"assets": {"directory": "path", "binding": "ASSETS"}` -- **If no \_worker.js**: You have an assets-only project - - Just use `"assets": {"directory": "path"}` without main field - -### 4. Handle \_worker.js (if present) - -If your build creates a \_worker.js file or directory: - -1. Create a `.assetsignore` file containing `_worker.js` -2. Update your build script to copy it to the output directory -3. This prevents the worker code from being served as a static asset - -### 5. Update Package.json Scripts - -First, ensure wrangler is updated to v4+ using your package manager: - -```bash -# npm -npm install --save-dev wrangler@^4.0.0 -# pnpm -pnpm add --save-dev wrangler@^4.0.0 -# yarn -yarn add --dev wrangler@^4.0.0 -# bun -bun add --dev wrangler@^4.0.0 -``` - -Then replace Pages commands with Workers equivalents: - -- `wrangler pages deploy` to `wrangler deploy` -- `wrangler pages dev` to `wrangler dev` - -Keep framework-specific commands unchanged (e.g., `astro dev`, `next dev`). - -### 6. Pages Functions Migration (if applicable) - -**ONLY if you have a `functions/` directory with .js/.ts files:** - -- **Always add** the Pages Functions build command to your build process -- Use: `wrangler pages functions build --outdir=/_worker.js/` -- This command converts Pages Functions to Workers format -- Update your main field to point to the compiled functions: `"main": "./path/to/_worker.js"` -- The presence of a `functions/` directory means you **must** include this build step - -### 7. Validation and Deployment - -1. Build your project to ensure it works -2. Run `wrangler deploy --dry-run` to validate configuration -3. Fix any issues identified -4. Deploy with user permission using `wrangler deploy` - -## Common Patterns - -### Assets-Only Projects - -Most static sites fall into this category: - -```jsonc -{ - "name": "my-site", - "assets": { "directory": "./dist" }, - "compatibility_date": "2025-06-05", -} -``` - -### Projects with Workers Scripts - -Sites with server-side logic or Pages Functions: - -```jsonc -{ - "name": "my-app", - "main": "./dist/_worker.js", - "assets": { - "directory": "./dist", - "binding": "ASSETS", - }, - "compatibility_date": "2025-06-05", -} -``` - -**Build script example for projects with Pages Functions:** - -```json -{ - "scripts": { - "build": "your-framework-build && wrangler pages functions build --outdir=./dist/_worker.js/" - } -} -``` - -## Important Notes - -- **Bindings**: Don't add KV, D1, or other bindings unless your build explicitly fails -- **Framework Messages**: Ignore informational logs about storage or sessions -- **Documentation**: Always check the official Cloudflare docs for the latest guidance -- **Flexibility**: Adapt these guidelines to your specific project structure - -## Migration Summary Format - -When complete, document: - -1. **Project Analysis**: What type of Pages project and its specific features -2. **Migration Steps**: What changes were made and why -3. **Validation**: How the migration was tested and verified \ No newline at end of file +- Update scripts and CI to use the selected framework's Workers commands or `wrangler dev` and `wrangler deploy` (and `wrangler preview` for branch previews where applicable). Keep framework-specific commands that own the build. Test the actual dev and deploy workflows with generated output absent. If a workflow needs a separate build, make that prerequisite explicit in the script, CI, or documented command sequence rather than relying on output left over from the Pages build. +- Run the actual deployment build from clean output; a generic project build might not produce the Worker. Run `wrangler deploy --dry-run` when Wrangler owns deployment, using the same effective config and build sequence. For other deployment tools, use their documented local or dry-run verification without deploying. Confirm the entrypoint, asset directory, and bindings; a dry-run does not confirm routing or dashboard settings. +- For translated splats, test the bare path (for example, `/api`), `/api/`, and a nested path on both includes and excludes. Test asset hits and misses, including when `not_found_handling` serves a fallback instead of invoking the Worker. +- If zone Cache Rules cached Pages-generated responses on the old custom domain, use Workers Cache and appropriate `Cache-Control` headers for eligible Worker-generated responses. Cache Rules can still apply to the Worker's `fetch()` subrequests. Verify generated-response caching in an approved test deployment or report it as unverified; do not assume local responses prove edge caching. +- Run Workers locally and compare it against the Pages baseline. Check status, redirects, meaningful body content, and relevant headers such as `Content-Type`, `Cache-Control`, and custom headers. Where applicable, test a static hit and miss, a deep link, an SSR response or API method, a function/asset collision, and assets and misses inside and outside includes and excludes. Compare a plain request and a browser-style `Sec-Fetch-Mode: navigate` request on routes that may be handled by either assets or the Worker. If you add a response shim, verify that an out-of-scope response still keeps its own cache and security headers. Request generated server paths and verify their contents are not served, even if a fallback returns `200`. +- Summarize what changed, which behavior you verified, and any mismatch or unverified assumption. List manual next steps for dashboard-only settings, secret setup, Worker Previews or Workers Builds, hostname cutover, and eventual Pages cleanup. A `pages.dev` hostname does not transfer to Workers; plan for any callers that still use it. Leave the current Pages deployment running. diff --git a/src/content/docs/workers/static-assets/migration-guides/migrate-from-pages.mdx b/src/content/docs/workers/static-assets/migration-guides/migrate-from-pages.mdx index 2ab29469f70..84e14951853 100644 --- a/src/content/docs/workers/static-assets/migration-guides/migrate-from-pages.mdx +++ b/src/content/docs/workers/static-assets/migration-guides/migrate-from-pages.mdx @@ -10,14 +10,7 @@ products: --- import { - Badge, - Description, - FileTree, - InlineBadge, - Render, Steps, - TabItem, - Tabs, WranglerConfig, TypeScriptExample, PackageManagers, @@ -27,11 +20,11 @@ You can deploy full-stack applications, including front-end static assets and ba Like Pages, requests for static assets on Workers are free, and [Pages Functions](#pages-functions) invocations are charged at the same rate as Workers, so you can expect [a similar cost structure](/workers/platform/pricing/#workers). -Unlike Pages, Workers has a distinctly broader set of features available to it, (including Durable Objects, Cron Triggers, and more comprehensive Observability). A complete list can be found at [the bottom of this page](#compatibility-matrix). +Unlike Pages, Workers has a broader set of features available, including Durable Objects, Workflows, Containers, Cron Triggers, and comprehensive Observability. A complete list is in the [compatibility matrix](#compatibility-matrix). ## Migration -Migrating from Cloudflare Pages to Cloudflare Workers is often a straightforward process. The following are some of the most common steps you will need to take to migrate your project. +Migrating from Cloudflare Pages to Cloudflare Workers is often straightforward. The following are the most common steps to migrate your project. ### Deployments and asset availability @@ -41,23 +34,27 @@ Review [Version skew and static assets](/workers/versions-and-deployments/versio ### Frameworks -If your Pages project uses [a popular framework](/workers/framework-guides/), most frameworks already have adapters available for Cloudflare Workers. Switch out any Pages-specific adapters for the Workers equivalent and follow any guidance that they provide. +If your Pages project uses [a popular framework](/workers/framework-guides/), most frameworks already have adapters available for Cloudflare Workers. Switch out any Pages-specific adapters for the Workers equivalent and follow the framework guide. + +For supported frameworks without an existing Workers configuration file, Wrangler can detect your framework, install the Workers adapter, and generate a `wrangler.jsonc` file with [`wrangler setup`](/workers/framework-guides/automatic-configuration/). + +`wrangler setup` refuses to run while a Pages configuration file with `pages_build_output_dir` is present. If Wrangler does not detect a framework, a `functions/` directory also identifies the project as Pages. For a supported framework, save the Pages configuration for rollback and move it out of the project before running setup. Otherwise, follow the [framework guide](/workers/framework-guides/) or migrate the Pages Functions manually. ### Project configuration -If your project doesn't already have one, create a [Wrangler configuration file](/workers/wrangler/configuration/) (either `wrangler.jsonc`, `wrangler.json` or `wrangler.toml`) in the root of your project. The two mandatory fields are: +If your project does not already have one, create a [Wrangler configuration file](/workers/wrangler/configuration/) (either `wrangler.jsonc`, `wrangler.json`, or `wrangler.toml`) in the root of your project. The two mandatory fields are: - [`name`](/workers/wrangler/configuration/#inheritable-keys) - Set this to the name of the Worker you wish to deploy to. This can be the same as your existing Pages project name, so long as it conforms to Workers' name restrictions (e.g. max length). + Set this to the name of the Worker you want to deploy to. This can be the same as your existing Pages project name, as long as it conforms to Workers' name restrictions (for example, max length). -- [`compatibility_date`](/workers/configuration/compatibility-dates/). +- [`compatibility_date`](/workers/configuration/compatibility-dates/) If you were already using [Pages Functions](/pages/functions/wrangler-configuration/#inheritable-keys), set this to the same date configured there. Otherwise, set it to the current date. #### Build output directory -Where you previously would configure a "build output directory" for Pages (in either a [Wrangler configuration file](/pages/functions/wrangler-configuration/#inheritable-keys) or in [the Cloudflare dashboard](/pages/configuration/build-configuration/#build-commands-and-directories)), you must now set the [`assets.directory`](/workers/static-assets/binding/#directory) value for a Worker project. +Where you previously configured a build output directory for Pages (in either a [Wrangler configuration file](/pages/functions/wrangler-configuration/#inheritable-keys) or in [the Cloudflare dashboard](/pages/configuration/build-configuration/#build-commands-and-directories)), set the [`assets.directory`](/workers/static-assets/binding/#directory) value for a Worker project. Before, with **Cloudflare Pages**: @@ -90,7 +87,7 @@ Now, with **Cloudflare Workers**: :::note -If your Worker will only contain assets and no Worker script, then you should remove the `"binding": "ASSETS"` field from your configuration file, since this is only valid if you have a Worker script indicated by a `"main"` property. See the [Assets binding](#assets-binding) section below. +If your Worker only contains assets and no Worker script, remove the `"binding": "ASSETS"` field from your configuration file, because it is only valid if you have a Worker script indicated by a `"main"` property. Refer to the [Assets binding](#assets-binding) section. ::: @@ -152,13 +149,13 @@ If you use a full-stack framework powered by [Pages Functions](/pages/functions/ ##### Pages Functions with an "advanced mode" `_worker.js` file -If you use Pages Functions with an ["advanced mode" `_worker.js` file](/pages/functions/advanced-mode/), you must first ensure this script doesn't get uploaded as a static asset. Either move `_worker.js` out of the static asset directory (recommended), or create [an `.assetsignore` file](/workers/static-assets/binding/#ignoring-assets) in the static asset directory and include `_worker.js` within it. +If you use Pages Functions with an ["advanced mode" `_worker.js` file](/pages/functions/advanced-mode/), ensure this script does not get uploaded as a static asset. Either move `_worker.js` out of the static asset directory (recommended), or create [an `.assetsignore` file](/workers/static-assets/binding/#ignoring-assets) in the static asset directory and include `_worker.js` within it. ```txt title="dist/client/.assetsignore" _worker.js ``` -Then, update your configuration file's `main` field to point to the location of this Worker script: +Then, update your configuration file's `main` field to point to the location of this Worker script. If your script calls `env.ASSETS.fetch()`, configure the `ASSETS` binding as shown below: @@ -167,9 +164,10 @@ Then, update your configuration file's `main` field to point to the location of "name": "my-worker", "compatibility_date": "$today", "main": "./dist/client/_worker.js", - "upload_source_maps": true, // or some other location if you moved the script out of the static asset directory + "upload_source_maps": true, "assets": { - "directory": "./dist/client/" + "directory": "./dist/client/", + "binding": "ASSETS" } } ``` @@ -186,9 +184,11 @@ If you use **Pages Functions with a [folder of `functions/`](/pages/functions/)* args={"pages functions build --outdir=./dist/worker/"} /> +The standalone Pages build command does not read compatibility settings from your Workers configuration. Pass the original Pages project's compatibility date with `--compatibility-date` and any compatibility flags with `--compatibility-flags`. + Although this command will remain available to you to run at any time, we do recommend considering using another framework if you wish to continue to use file-based routing. [HonoX](https://github.com/honojs/honox) is one popular option. -Once the Worker script has been compiled, you can update your configuration file's `main` field to point to the location it was built to: +Set `main` to the compiled Worker script and configure the `ASSETS` binding. The compiled script uses `env.ASSETS.fetch()` when no Function handles a request or middleware passes the request through without a response: @@ -199,7 +199,8 @@ Once the Worker script has been compiled, you can update your configuration file "main": "./dist/worker/index.js", "upload_source_maps": true, "assets": { - "directory": "./dist/client/" + "directory": "./dist/client/", + "binding": "ASSETS" } } ``` @@ -208,9 +209,13 @@ Once the Worker script has been compiled, you can update your configuration file ##### `_routes.json` and Pages Functions middleware -If you authored [a `_routes.json` file](/pages/functions/routing/#create-a-_routesjson-file) in your Pages project, or used [middleware](/pages/functions/middleware/) in Pages Functions, you must pay close attention to the configuration of your Worker script. Pages would default to serving your Pages Functions ahead of static assets and `_routes.json` and Pages Functions middleware allowed you to customize this behavior. +If you authored [a `_routes.json` file](/pages/functions/routing/#create-a-_routesjson-file) in your Pages project, or used [middleware](/pages/functions/middleware/) in Pages Functions, review how your Worker script routes requests. Pages defaults to running Pages Functions ahead of static assets, and `_routes.json` and middleware customize that behavior. -Workers, on the other hand, will default to serving static assets ahead of your Worker script, unless you have configured [`assets.run_worker_first`](/workers/static-assets/routing/worker-script/#run-your-worker-script-first). This option is required if you are, for example, performing any authentication checks or logging requests before serving static assets. +By default, Workers serves a matching static asset before invoking your Worker script. Set [`assets.run_worker_first`](/workers/static-assets/routing/worker-script/#run-your-worker-script-first) to `true` to run your script before static assets on every request. + +If you pass an array of route patterns (such as `["/api", "/api/*", "!/api/docs", "!/api/docs/*"]`), positive matches run your Worker script first and negative (`!`) matches go directly to static assets. Paths that match neither keep the default behavior: a request can still invoke your Worker script if no asset matches and [`not_found_handling`](/workers/static-assets/#routing-behavior) does not serve a fallback. In Pages `_routes.json`, `/api/*` also matches `/api`, but in `run_worker_first` it does not. List the bare path separately for any include or exclude that needs to match it. + +Unlike `_routes.json`, an array does not limit Worker invocations to the listed paths. To preserve where your Pages Functions and middleware run, apply the original include and exclude rules in your Worker before dispatching to the compiled Functions. For requests outside that scope, return `env.ASSETS.fetch(request)` without dispatching to the Functions. @@ -222,16 +227,19 @@ Workers, on the other hand, will default to serving static assets ahead of your "upload_source_maps": true, "assets": { "directory": "./dist/client/", - "run_worker_first": true + "binding": "ASSETS", + "run_worker_first": ["/api", "/api/*", "!/api/docs", "!/api/docs/*"] } } ``` +After migrating your routing rules, remove `_routes.json` from your static asset directory or add `/_routes.json` to [`.assetsignore`](/workers/static-assets/binding/#ignoring-assets). Workers does not exclude this file from static asset uploads by default. + ##### Starting from scratch -If you wish to, you can start a new Worker script from scratch and take advantage of all of Wrangler's and the latest runtime features (e.g. [`WorkerEntrypoint`s](/workers/runtime-apis/bindings/service-bindings/rpc/), [TypeScript support](/workers/languages/typescript/), [bundling](/workers/wrangler/bundling), etc.): +You can also start a new Worker script from scratch and use Wrangler's latest runtime features, such as [`WorkerEntrypoint`](/workers/runtime-apis/bindings/service-bindings/rpc/), [TypeScript support](/workers/languages/typescript/), and [bundling](/workers/wrangler/bundling/): @@ -311,17 +319,17 @@ If you had customized [placement](/workers/configuration/placement/), or set a [ ### Variables, secrets and bindings -[Variables](/workers/configuration/environment-variables/) and [bindings](/workers/runtime-apis/bindings/) can be set in your [Wrangler configuration file](/workers/wrangler/configuration/) and are made available in your Worker's environment (`env`). [Secrets](/workers/configuration/secrets/) can uploaded with Wrangler or defined in the Cloudflare dashboard for [production](/workers/configuration/secrets/#adding-secrets-to-your-project) and [`.dev.vars` for local development](/workers/configuration/secrets/#local-development-with-secrets). +[Variables](/workers/configuration/environment-variables/) and [bindings](/workers/runtime-apis/bindings/) can be set in your [Wrangler configuration file](/workers/wrangler/configuration/) and are made available in your Worker's environment (`env`). [Secrets](/workers/configuration/secrets/) can be uploaded with Wrangler or defined in the Cloudflare dashboard for [production](/workers/configuration/secrets/#adding-secrets-to-your-project) and [`.dev.vars` for local development](/workers/configuration/secrets/#local-development-with-secrets). If you are [using Workers Builds](#builds), ensure you also [configure any variables relevant to the build environment there](/workers/ci-cd/builds/configuration/). Unlike Pages, Workers does not share the same set of runtime and build-time variables. ### Wrangler commands -Where previously you used [`wrangler pages dev`](/workers/wrangler/commands/pages/#pages-dev) and [`wrangler pages deploy`](/workers/wrangler/commands/general/#deploy), now instead use [`wrangler dev`](/workers/wrangler/commands/general/#dev) and [`wrangler deploy`](/workers/wrangler/commands/general/#deploy). Additionally, if you are using a Vite-powered framework, [our new Vite plugin](/workers/vite-plugin/) may be able offer you an even simpler development experience. +Where previously you used [`wrangler pages dev`](/workers/wrangler/commands/pages/#pages-dev) and [`wrangler pages deploy`](/workers/wrangler/commands/pages/#pages-deploy), now instead use [`wrangler dev`](/workers/wrangler/commands/workers/#dev) and [`wrangler deploy`](/workers/wrangler/commands/workers/#deploy). Additionally, if you are using a Vite-powered framework, the [Cloudflare Vite plugin](/workers/vite-plugin/) may be able to offer you an even simpler development experience. -:::note[Wrangler uses a different default port for the local development] +:::note[Wrangler uses a different default port for local development] -`wrangler pages dev` will, by default, expose the local development server at `http://localhost:8788`, whereas `wrangler dev` will expose it at `http://localhost:8787/`. +`wrangler pages dev` exposes the local development server at `http://localhost:8788` by default, whereas `wrangler dev` exposes it at `http://localhost:8787/`. You can customize the port using `--port`. ::: @@ -377,6 +385,14 @@ For new Workers created with Workers Builds, preview builds use `wrangler previe [`_headers`](/workers/static-assets/headers/) and [`_redirects`](/workers/static-assets/redirects/) files are supported natively in Workers with static assets. Ensure that, just like for Pages, these files are included in the static asset directory of your project. +### Caching and Cache Rules + +Static assets on Workers are cached automatically across Cloudflare's network. By default, matching assets are served without invoking your Worker script. + +On Pages, zone-level [Cache Rules](/cache/how-to/cache-rules/) on a custom domain can cache responses from Pages Functions or an [advanced mode `_worker.js`](/pages/functions/advanced-mode/). On Workers, your Worker runs [before the zone cache](/workers/reference/how-the-cache-works/), so Cache Rules do not cache the responses it generates. To cache eligible Worker-generated responses, enable [Workers Cache](/workers/cache/) with `"cache": { "enabled": true }` in Wrangler and set appropriate `Cache-Control` headers on the responses you want to cache. + +Cache Rules still apply to subrequests made with `fetch()`. Whether your Worker's cache settings override those rules depends on its compatibility flags. Refer to [How Workers interact with Cache Rules](/cache/interaction-cloudflare-products/workers-cache-rules/). + ### pages.dev Where previously you were offered a `pages.dev` subdomain for your Pages project, you can now configure a personalized `workers.dev` subdomain for all of your Worker projects. You can [configure this subdomain in the Cloudflare dashboard](/workers/configuration/routing/workers-dev/#configure-workersdev), and opt-in to using it with the [`workers_dev` option](/workers/configuration/routing/workers-dev/#disabling-workersdev-in-the-wrangler-configuration-file) in your configuration file. @@ -397,7 +413,7 @@ Where previously you were offered a `pages.dev` subdomain for your Pages project ### Custom domains -If your domain's nameservers are managed by Cloudflare, you can, like Pages, configure a [custom domain](/workers/configuration/routing/custom-domains/) for your Worker. Additionally, you can also configure a [route](/workers/configuration/routing/routes/) if you only wish to some subset of paths to be served by your Worker. +If your domain's nameservers are managed by Cloudflare, you can, like Pages, configure a [custom domain](/workers/configuration/routing/custom-domains/) for your Worker. Additionally, you can configure a [route](/workers/configuration/routing/routes/) if you only want a subset of paths to be served by your Worker. :::note @@ -407,23 +423,23 @@ Unlike Pages, Workers does not support any domain whose nameservers are not mana ### Rollout -Once you have validated the behavior of Worker, and are satisfied with the development workflows, and have migrated all of your production traffic, you can delete your Pages project in the Cloudflare dashboard or with Wrangler: +Once you have validated the behavior of your Worker, are satisfied with the development workflows, and have migrated all of your production traffic, you can delete your Pages project in the Cloudflare dashboard or with Wrangler: ## Migrate your project using an AI coding assistant -You can add the following [experimental prompt](https://developers.cloudflare.com/workers/prompts/pages-to-workers.txt) in your preferred coding assistant (e.g. Claude Code, Cursor) to make your project compatible with Workers: +You can add the following [migration prompt](/workers/prompts/pages-to-workers.txt) in your coding assistant (for example, Claude Code or Cursor) to help migrate your project to Workers: -``` +```txt https://developers.cloudflare.com/workers/prompts/pages-to-workers.txt ``` -You can also use the Cloudflare Documentation [MCP server](https://github.com/cloudflare/mcp-server-cloudflare/tree/main/apps/docs-ai-search) in your coding assistant to provide better context to your LLM when building with Workers, which includes this prompt when you ask to migrate from Pages to Workers. +You can also connect the [Cloudflare documentation MCP server](/agents/model-context-protocol/cloudflare/servers-for-cloudflare/) (`https://docs.mcp.cloudflare.com/mcp`) in your coding assistant so your agent has up-to-date context when migrating from Pages to Workers. ## Compatibility matrix -This compatibility matrix compares the features of Workers and Pages. Unless otherwise stated below, what works in Pages works in Workers, and what works in Workers works in Pages. Think something is missing from this list? [Open a pull request](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/workers/static-assets/compatibility-matrix.mdx) or [create a GitHub issue](https://github.com/cloudflare/cloudflare-docs/issues/new). +This compatibility matrix compares the features of Workers and Pages. Unless otherwise stated, what works in Pages works in Workers, and what works in Workers works in Pages. Think something is missing from this list? [Open a pull request](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/workers/static-assets/migration-guides/migrate-from-pages.mdx) or [create a GitHub issue](https://github.com/cloudflare/cloudflare-docs/issues/new). **Legend**
✅: Supported
@@ -438,7 +454,7 @@ This compatibility matrix compares the features of Workers and Pages. Unless oth | [Rollbacks](/workers/versions-and-deployments/rollbacks/) | ✅ | ✅ | | [Gradual Deployments](/workers/versions-and-deployments/) | ✅ | ❌ | | [Preview URLs](/workers/previews/) | ✅ | ✅ | -| [Testing tools](/workers/testing) | ✅ | ✅ | +| [Testing tools](/workers/testing/) | ✅ | ✅ | | [Local Development](/workers/local-development/) | ✅ | ✅ | | [Remote Development (`--remote`)](/workers/wrangler/commands/) | ✅ | ❌ | | [Quick Editor in Dashboard](https://blog.cloudflare.com/improved-quick-edit) | ✅ | ❌ | @@ -454,14 +470,16 @@ This compatibility matrix compares the features of Workers and Pages. Unless oth | [Logpush](/workers/observability/logs/logpush/) | ✅ | ❌ | | [Tail Workers](/workers/observability/logs/tail-workers/) | ✅ | ❌ | | [Real-time logs](/workers/observability/logs/real-time-logs/) | ✅ | ✅ | -| [Source Maps](/workers/observability/source-maps/) | ✅ | ❌ | +| [Source Maps](/workers/observability/source-maps/) | ✅ | ✅ [^3] | | **Runtime APIs & Compute Models** | | | | [Node.js Compatibility Mode](/workers/runtime-apis/nodejs/) | ✅ | ✅ | -| [Durable Objects](/durable-objects/api/) | ✅ | 🟡 [^3] | +| [Durable Objects](/durable-objects/api/) | ✅ | 🟡 [^4] | +| [Workflows](/workflows/) | ✅ | 🟡 [^5] | +| [Containers](/containers/) | ✅ | ❌ | | [Cron Triggers](/workers/configuration/cron-triggers/) | ✅ | ❌ | | **Bindings** | | | | [AI](/workers-ai/get-started/workers-wrangler/#2-connect-your-worker-to-workers-ai) | ✅ | ✅ | -| [Analytics Engine](/analytics/analytics-engine) | ✅ | ✅ | +| [Analytics Engine](/analytics/analytics-engine/) | ✅ | ✅ | | [Assets](/workers/static-assets/binding/) | ✅ | ✅ | | [Browser Run](/browser-run/) | ✅ | ✅ | | [D1](/d1/worker-api/) | ✅ | ✅ | @@ -476,6 +494,7 @@ This compatibility matrix compares the features of Workers and Pages. Unless oth | [R2](/r2/) | ✅ | ✅ | | [Rate Limiting](/workers/runtime-apis/bindings/rate-limit/) | ✅ | ❌ | | [Secrets](/workers/configuration/secrets/) | ✅ | ✅ | +| [Secrets Store](/secrets-store/) | ✅ | ❌ | | [Service bindings](/workers/runtime-apis/bindings/service-bindings/) | ✅ | ✅ | | [Vectorize](/vectorize/get-started/intro/#3-bind-your-worker-to-your-index) | ✅ | ✅ | | **Builds (CI/CD)** | | | @@ -483,11 +502,11 @@ This compatibility matrix compares the features of Workers and Pages. Unless oth | [Build Watch Paths](/workers/ci-cd/builds/build-watch-paths/) | ✅ | ✅ | | [Build Caching](/workers/ci-cd/builds/build-caching/) | ✅ | ✅ | | [Deploy Hooks](/workers/ci-cd/builds/deploy-hooks/) | ✅ | ✅ | -| [Branch Deploy Controls](/pages/configuration/branch-build-controls/) | 🟡 [^4] | ✅ | -| [Custom Branch Aliases](/pages/how-to/custom-branch-aliases/) | ✅ [^5] | ✅ | +| [Branch Deploy Controls](/pages/configuration/branch-build-controls/) | 🟡 [^6] | ✅ | +| [Custom Branch Aliases](/pages/how-to/custom-branch-aliases/) | ✅ [^7] | ✅ | | **Pages Functions** | | | -| [File-based Routing](/pages/functions/routing/) | 🟡 [^6] | ✅ | -| [Pages Plugins](/pages/functions/plugins/) | 🟡 [^7] | ✅ | +| [File-based Routing](/pages/functions/routing/) | 🟡 [^8] | ✅ | +| [Pages Plugins](/pages/functions/plugins/) | 🟡 [^9] | ✅ | | **Domain Configuration** | | | | [Custom domains](/workers/configuration/routing/custom-domains/#add-a-custom-domain) | ✅ | ✅ | | [Custom subdomains](/workers/configuration/routing/custom-domains/#set-up-a-custom-domain-in-the-dashboard) | ✅ | ✅ | @@ -496,14 +515,18 @@ This compatibility matrix compares the features of Workers and Pages. Unless oth [^1]: Workers can use Early Hints when the zone setting is turned on. Your Worker must send the appropriate `Link` headers. For more information, refer to the [103 Early Hints](/workers/examples/103-early-hints/) example. -[^2]: Middleware can be configured via the [`run_worker_first`](/workers/static-assets/binding/#run_worker_first) option, but is charged as a normal Worker invocation. We plan to explore additional related options in the future. +[^2]: The [`run_worker_first`](/workers/static-assets/binding/#run_worker_first) option controls whether your Worker script runs before static assets. With an array of patterns, a request that matches none of the patterns can still invoke the script if no asset matches and `not_found_handling` does not serve a fallback. Requests routed to the Worker script are billed as normal Worker invocations. + +[^3]: [Pages Functions source maps](/pages/functions/source-maps/) require explicit opt-in (`upload_source_maps: true` or `--upload-source-maps`) and only apply to real-time logs. [Workers source maps](/workers/observability/source-maps/) upload by default starting in Wrangler 4.150.0. On earlier versions, set `upload_source_maps: true` to opt in. Workers also supports source maps for Tail Workers and [Workers Issues](/workers/observability/issues/). + +[^4]: To [use Durable Objects with your Cloudflare Pages project](/pages/functions/bindings/#durable-objects), you must create a separate Worker with a Durable Object and then declare a binding to it in both your Production and Preview environments. Using Durable Objects with Workers is simpler and recommended. -[^3]: To [use Durable Objects with your Cloudflare Pages project](/pages/functions/bindings/#durable-objects), you must create a separate Worker with a Durable Object and then declare a binding to it in both your Production and Preview environments. Using Durable Objects with Workers is simpler and recommended. +[^5]: To [call Workflows from Pages](/workflows/build/call-workflows-from-pages/), you must deploy your Workflow in a separate Worker and invoke it via a Service Binding or `fetch()`. Defining Workflows directly inside a Static Assets Worker is simpler and recommended. -[^4]: Workers Builds supports enabling [preview builds](/workers/ci-cd/builds/build-branches/#configure-preview-builds), though does not yet have the same level of configurability as Pages does. +[^6]: Workers Builds supports enabling [preview builds](/workers/ci-cd/builds/build-branches/#configure-preview-builds), though it does not have the same level of configurability as Pages. -[^5]: Use [custom domain Preview URLs](/workers/previews/custom-domains/) to serve branch Previews on your own domain. Unlike Pages, where you can point any hostname at a branch, Workers serves each Preview at `.`, and the Preview name defaults to the branch name. Cloudflare creates a wildcard DNS record and certificate for the domain you choose. +[^7]: Use [custom domain Preview URLs](/workers/previews/custom-domains/) to serve branch Previews on your own domain. Unlike Pages, where you can point any hostname at a branch, Workers serves each Preview at `.`, and the Preview name defaults to the branch name. Cloudflare creates a wildcard DNS record and certificate for the domain you choose. -[^6]: Workers [supports popular frameworks](/workers/framework-guides/), many of which implement file-based routing. Additionally, you can use Wrangler to [compile your folder of `functions/`](#pages-functions-with-a-functions-folder) into a Worker to help ease the migration from Pages to Workers. +[^8]: Workers [supports popular frameworks](/workers/framework-guides/), many of which implement file-based routing. Additionally, you can use Wrangler to [compile your folder of `functions/`](#pages-functions-with-a-functions-folder) into a Worker to help ease the migration from Pages to Workers. -[^7]: As in 6, Wrangler can [compile your Pages Functions into a Worker](#pages-functions-with-a-functions-folder). Or if you are starting from scratch, everything that is possible with Pages Functions can also be achieved by adding code to your Worker or by using framework-specific plugins for relevant third party tools. +[^9]: As with file-based routing, Wrangler can [compile your Pages Functions into a Worker](#pages-functions-with-a-functions-folder). Or if you are starting from scratch, everything that is possible with Pages Functions can also be achieved by adding code to your Worker or by using framework-specific plugins for relevant third-party tools.