Skip to content
AnswerWell geo Documentation

Research · 9 min read · Answerwell

Forward HTTP Traffic, Workers Middleware, Context, and Limits

How Gateway Forward invokes Workers on permitted HTTP traffic: policy order, handle() and next(), identity context, templates, and known limits.

This page summarizes Cloudflare documentation on Gateway Forward: running your own Cloudflare Workers code on HTTP traffic that Gateway already permits, without operating a separate HTTP proxy. The Forward action is in public beta on all Zero Trust plans; Workers usage is subject to Workers pricing.

Cloudflare Gateway now integrates with Cloudflare Workers in public beta on all Zero Trust plans. You can use the Forward action in Gateway HTTP policies to run your own code on matching, permitted traffic without managing a separate proxy.

— Cloudflare, Gateway and Workers integration is now in public beta

Forward action: when Gateway runs your Worker on HTTP traffic

Section titled “Forward action: when Gateway runs your Worker on HTTP traffic”

The Forward action invokes a Worker on permitted HTTP traffic. Use it to implement request and response transformations, application-specific controls, or background tasks without operating a separate HTTP proxy.

Forward invokes a Worker on permitted HTTP traffic. The Worker can modify a request before sending it to its original destination, transform the response, return a synthetic response, or run background work.

— Cloudflare, HTTP policies — Forward Beta

Typical uses include transforming requests and responses, showing a coaching page, or running background work such as Slack notifications or R2 captures. The Worker receives the request and Gateway context, including connection metadata, user identity, and device posture when available.

Goal Forward fits when… Prefer built-in Gateway policies when…
Block access You need custom UX (coaching page) or logic Gateway selectors cannot express A Block HTTP policy is enough
Transform JSON/HTML You control the endpoint schema and accept rewrite trade-offs DLP or WAF rules cover the need
Audit / notify Narrow scope; background work via waitUntil() is acceptable You need guaranteed retention (use Queues or Workflows)
Identity / posture gate Requirements need custom code beyond selectors Built-in identity and device posture selectors suffice

Policy order: where Forward sits among HTTP request, body, and response inspection

Section titled “Policy order: where Forward sits among HTTP request, body, and response inspection”

Forward policies run in a separate phase after HTTP request policies and before body policies and inspection. Gateway invokes the Worker selected by the first matching Forward policy, in order of precedence.

Gateway evaluates Forward policies after HTTP request policies and before body policies and inspection. It invokes the Worker selected by the first matching Forward policy, in order of precedence.

— Cloudflare, Forward traffic — How it works

Gateway inspects the original request body before delivering it to the Worker. A Block decision from body policies or inspection can interrupt an already-running Worker. Gateway inspects the final response (including synthetic responses) before returning it to the user.

For Data Loss Prevention (DLP), the same ordering matters:

When you use Forward to invoke a Worker, Gateway scans the original request body before delivering it to the Worker. A DLP Block decision can interrupt an already-running Worker.

Gateway scans the final response after the Worker. Modified request bytes are not scanned again before reaching the origin.

— Cloudflare, DLP with the Forward action Beta

Common conclusion: Your Worker runs on the original body Gateway already inspected; redaction or field replacement in the Worker cannot bypass request-side DLP. Bytes you add to a permitted request do not get another request-side DLP scan before the origin sees them.

Forward policy matching: what can and cannot select a Worker

Section titled “Forward policy matching: what can and cannot select a Worker”

Use request metadata selectors, identity, and device posture conditions to select traffic. Body inspection results, DLP matches, and response selectors cannot select a Worker.

— Cloudflare, HTTP policies — Forward Beta

Match Forward policies with Host, URL, HTTP Method, identity, and device posture—not on DLP match results or response metadata.

GatewayMiddleware.handle(): request, context, and next() semantics

Section titled “GatewayMiddleware.handle(): request, context, and next() semantics”

Gateway calls the named GatewayMiddleware entrypoint’s handle(request, context, next) method through Workers RPC. The exported class name must stay GatewayMiddleware.

Parameter Role
request Original HTTP Request, including its body stream
context Gateway metadata describing the original request; modifying the Request does not update context
next(request) Sends a request to its original destination through Gateway and returns the upstream Response

next(request) sends a request to its original destination through Gateway and returns the upstream Response. Gateway establishes the upstream connection when the Worker calls next().

The Worker can modify the method, headers, cookies, or body before calling next(). It can modify the upstream response or return a synthetic response without calling next(). Call next() at most once per invocation.

— Cloudflare, Forward traffic — How it works

Call next() at most once per invocation. You cannot use it to change the destination URL or host, retry an upstream request, or send requests to several destinations. A normal Workers fetch() is an independent subrequest and does not inherit the user’s Gateway policies or egress IP—use next() to continue the user’s request with Gateway’s routing and egress configuration.

Return a final status from 200 to 599. For HEAD or statuses 204, 205, and 304, return no body. Invocation errors, Worker errors, or communication failures fail closed: Gateway does not bypass the Worker and forward the original request.

Available context: identity, device posture, and error handling

Section titled “Available context: identity, device posture, and error handling”

Gateway passes context as the second argument to GatewayMiddleware.handle(request, context, next).

Context describes the original request when Gateway selects a Forward policy. Modifying the Request does not update context.

Field names use camelCase. Optional fields are omitted when unavailable, and empty metadata lists are omitted. Availability depends on the connection method, destination, and authenticated session. Check optional values before using them.

— Cloudflare, Available context

Gateway still invokes the Worker if it cannot retrieve identity or device posture. Uncaught errors from context.identity() or context.devicePosture() can yield HTTP 500 from Gateway.

Use try/catch to choose how your Worker handles these errors. The example returns HTTP 503 for retrieval errors and HTTP 403 when identity or a required posture check is missing.

If your application deliberately allows traffic when Gateway cannot retrieve identity or posture, return next(request) from the catch block.

— Cloudflare, Available context — Handle identity and posture errors

When requirements map to built-in identity or device posture selectors, configure them in the Gateway filtering policy and reserve Worker logic for custom rules—see the identity and posture example.

Set up Forward: Worker project, deploy, and HTTP policy

Section titled “Set up Forward: Worker project, deploy, and HTTP policy”
  1. Have a Cloudflare account with Workers, Gateway HTTP filtering, TLS decryption, and a trusted root certificate on test devices. Use the same account for Workers and Gateway. See prerequisites.

  2. Create a Worker project (for example gateway-worker), set workers_dev and preview_urls to false if you do not want public dev URLs, and export GatewayMiddleware with handle() as in Set up Forward.

  3. For TypeScript, install @cloudflare/zt-types (2026.10.1 or later) as a dev dependency for GatewayMiddlewareContext and GatewayMiddlewareNext; import WorkerEntrypoint from cloudflare:workers.

  4. Deploy with Wrangler, then in Cloudflare One go to Traffic controls → Firewall policies → HTTP, add a scoped policy (host, path, method, user group), choose Forward, and select the deployed Worker—not a workers.dev URL.

  5. From a test device, confirm behavior (for example the pass-through example sets x-gateway-worker: gateway-worker on the response).

You can also create rules via API with action: "forward" and rule_settings.forward.worker_id (32-character Worker ID). See Configure with the API and the Create a Zero Trust Gateway rule endpoint.

Worker templates: starting points for Forward policies

Section titled “Worker templates: starting points for Forward policies”

Worker templates are single-purpose scripts using GatewayMiddleware.handle(request, context, next):

Template Purpose
Send a Slack notification Background alert after a selected request completes
Capture a screenshot Independent browser visit to a fixed public URL; save image to R2
Capture a downloaded file Copy attachments up to 25 MiB to R2 via Content-Disposition
Watermark HTML pages Visible user label on uncompressed HTML 200 responses
Store headers and bodies as JSON Archive bounded JSON bodies (256 KiB) and selected headers in R2
Display a coaching page Synthetic HTML without calling next()
Redact a JSON field Replace a top-level field before upstream delivery

Scope policies to specific methods and paths—page loads generate many requests. Background tasks should use this.ctx.waitUntil(); they are not a durable queue. For retries or long processing, use Queues or Workflows per Known limitations.

The coaching page template returns a synthetic response without calling next(), so Gateway never contacts the original destination for matching HTML GET requests. Method and Accept checks only decide when to show the page—they are not access controls because clients can change headers. Use Gateway Block policies when you must prevent access.

  • Download capture skips files over 25 MiB, compressed bodies, and non-attachment responses; cloning can buffer memory—keep policies narrow (Capture a downloaded file).
  • JSON redaction is field-based, not full DLP; rewriting JSON can break signatures (Redact a JSON field).
  • Screenshot does not inherit the user’s cookies, authorization, or Gateway session—it reflects a public page (Capture a screenshot).

Known limitations: protocols, Workers VPC, and deleted Workers

Section titled “Known limitations: protocols, Workers VPC, and deleted Workers”
Area Behavior
HTTPS Traffic must be decrypted; Do Not Inspect bypasses Forward
WebSocket / CONNECT Connect directly to upstream; Worker is not invoked
Workers VPC egress HTTP from compute matching Forward is dropped, not invoked—exclude from Forward policies
Policy lifecycle Worker ID resolved when policy is saved; deleted Worker → matching requests return HTTP 500
Forward matching Request metadata, identity, posture only—not body DLP or response selectors

Gateway drops HTTP traffic sent from the Cloudflare compute platform through Workers VPC if it matches a Forward policy. Gateway does not invoke the selected Worker.

— Cloudflare, Forward traffic — Known limitations

Related: Workers VPC can route Worker egress through Gateway so DNS, HTTP, Network, and egress policies apply to programmatic compute—the inverse path from user traffic Forward.

Troubleshooting Forward: Worker not running or HTTP 500

Section titled “Troubleshooting Forward: Worker not running or HTTP 500”

If the Worker does not run, confirm Gateway HTTP filtering, HTTPS decryption, permit policies, and that no earlier Forward or Do Not Inspect policy matches. If requests fail after enablement, verify GatewayMiddleware, a returned Response, next() at most once, valid status codes, and Workers Logs. See Forward troubleshooting and Worker errors with the Forward action.

Deleting a Worker leaves Forward policies pointing at it; update the policy or delete it before removal. Saving a policy that references a deleted Worker can fail with API error 2294.

  • Assuming fetch() inside the Worker uses the end user’s Gateway path or egress.
  • Calling next() more than once or expecting to retarget the upstream host.
  • Using Worker redaction to evade request-side DLP (inspection order prevents this).
  • Broad host-level Forward policies on pages that load dozens of assets (notifications, captures).
  • Treating coaching-page header checks as enforcement instead of Block policies.
  1. Confirm test devices send HTTP traffic through Cloudflare Gateway with TLS decryption enabled per Forward traffic prerequisites.
  2. Deploy a pass-through Worker that sets a verifiable response header and attach it with a narrow Forward policy as described in Set up Forward.
  3. Trigger permitted traffic on the scoped host and path; confirm the header and review Gateway / Worker logs if it is missing.
  4. Test a deliberate Block on the same traffic and confirm the Worker is not invoked, per HTTP policies — Forward Beta.
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about so it can be corrected or explained.