Skip to content

Next.js on Cloudflare Workers (OpenNext): generated guard's egress: true runs the Worker out of memory #514

Open

Description

@matchlessweb

Summary

On a Next.js app deployed to Cloudflare Workers through OpenNext, the guard that setup generates sets egress: true. The first App Router route handler that makes an outbound fetch() then runs the Worker out of memory (Worker exceeded memory limit, HTTP 503). Changing only that line to egress: false fixes it.

A second, smaller issue with the same setup is at the end: the shared guard promise in the Next.js template can go dead on Workers, which silently turns screening off for that isolate.

Environment

  • @patchstack/connect 0.5.83. Guard generated by npx @patchstack/connect setup --widget, composed into middleware.ts (Edge runtime), plus npx @patchstack/connect protect wrapping 15 App Router route handlers.
  • next 16.4.6 (App Router, middleware.ts on the Edge runtime)
  • @opennextjs/cloudflare 1.20.18, wrangler 4.166.0
  • Worker compatibility_date 2025-08-01, flags nodejs_compat and global_fetch_strictly_public

What happened

  1. Deployed with the generated guard file unchanged.
  2. Pages and the middleware worked.
  3. The first signed-in request to a route handler that calls fetch() to an external HTTPS API failed with Error: Worker exceeded memory limit and a 503. Every such route failed the same way.

Reproduced locally

  1. opennextjs-cloudflare build, then wrangler dev on the output.
  2. Request a route handler that does an outbound fetch().
  3. workerd prints JavaScript heap out of memory and The Workers runtime crashed unexpectedly and is being restarted.
  4. Same build with egress: false: the route works.

The generated guard (patchstack.next.ts, site UUID replaced)

// Server-only helpers for Next.js middleware and App Router handlers.
import { createProtection } from "@patchstack/connect/protect";
import fallbackRules from "./patchstack.rules.json";

const PS_SITE_UUID = "<site uuid>";
type Protection = Awaited<ReturnType<typeof createProtection>>;
let _protection: Promise<Protection> | undefined;
let warned = false;

async function getProtection() {
  if (!_protection) {
    _protection = buildProtection().catch((error) => {
      _protection = undefined;
      throw error;
    });
  }
  return _protection;
}

async function buildProtection() {
  const mode = (typeof process === "undefined" ? undefined : process.env.PATCHSTACK_MODE) === "dry-run" ? "dry-run" : "block";
  const siteUuid = PS_SITE_UUID.startsWith("__") ? (typeof process === "undefined" ? undefined : process.env.PATCHSTACK_SITE_UUID) : PS_SITE_UUID;
  const token = (typeof process === "undefined" ? undefined : process.env.PATCHSTACK_WAF_TOKEN);
  const refreshMs = (typeof process === "undefined" ? undefined : process.env.PATCHSTACK_ENVIRONMENT) === "sandbox" ? 15000 : 300000;
  const common = { mode, egress: true, refreshMs } as const;
  return createProtection(
    siteUuid
      ? { ...common, siteUuid, rules: fallbackRules as never, cacheDir: ".patchstack" }
      : token
        ? { ...common, token, cacheDir: ".patchstack" }
        : { ...common, rules: fallbackRules as never },
  );
}

export async function getPatchstackProtection() {
  return getProtection().catch((error: unknown) => {
    if (!warned) {
      warned = true;
      console.warn(
        "[patchstack] protection is unavailable; traffic may pass through unscreened until a later attempt succeeds. Reported once per process. Cause: " +
          (error instanceof Error ? error.message : String(error)),
      );
    }
    return null;
  });
}

// The handler's expression is evaluated once; its rejection remains the application's error.
export async function screenPatchstackResponse(
  response: Response | Promise<Response>,
  request: Request,
  protection: Protection | null,
): Promise<Response> {
  return protection ? protection.screenResponse(await response, request) : response;
}

Composed into middleware.ts (matcher "/:path*"; the rest of the middleware is the app's own auth and makes no outbound fetch):

import { getPatchstackProtection } from './patchstack.next'

export async function middleware(request: NextRequest) {
  // #region patchstack-next-composed
  const psProtection = await getPatchstackProtection();
  const psBlocked = psProtection && await psProtection.fetchGuard()(request);
  if (psBlocked) return psBlocked;
  // #endregion
  // ... app's auth checks
}

A route handler as protect wrapped it, the one used for the local reproduction:

import { getPatchstackProtection, screenPatchstackResponse } from "../../../patchstack.next";
import { NextResponse } from "next/server";

export async function GET(psRequest: Request) {
  // #region patchstack-next-route
  const psProtection = await getPatchstackProtection();
  const psBlocked = psProtection && await psProtection.fetchGuard()(psRequest);
  if (psBlocked) return psBlocked;
  // #endregion

  let body = BUILT_IN_RANGES;
  try {
    const res = await fetch("https://api.cloudflare.com/client/v4/ips", { signal: AbortSignal.timeout(5000) });
    // ... parse and validate into body
  } catch {}
  return screenPatchstackResponse((NextResponse.json(body)), psRequest, psProtection);
}

Likely cause (not confirmed)

installEgressGuard captures globalThis.fetch when installed and replaces it with its wrapper. Next.js also patches globalThis.fetch (patch-fetch), and OpenNext adds its own handling on Workers. The app also ends up with two copies of the guard, one in the middleware bundle and one in the server bundle. We believe the wrappers call each other repeatedly, or stack up, until memory runs out. No stack trace was captured, so this is a lead, not a finding.

Suggestions

  • When generating a guard for Next.js on Workers/OpenNext, write egress: false. Alternatively, detect the runtime (no node:dns lookup, navigator.userAgent === "Cloudflare-Workers", or globalThis.fetch.__nextPatched) and don't wrap a fetch that is already patched.
  • On Workers, Cloudflare's global_fetch_strictly_public compatibility flag already refuses fetches to private and internal addresses. setup or protect could suggest it there instead of egress.
  • protect --check could warn when egress is on for a Workers target.

Second issue: a cancelled request leaves the shared guard promise dead

The Next.js template keeps one in-flight createProtection() promise per process and shares it across requests. On Workers, if the request that started the build is cancelled (for example, a browser navigating away mid-load), other requests can't await that promise. They fail with This promise was created by a request that has since ended.

The template's .catch that should clear the cached promise never runs in that case. So every later request in that isolate gets null from getPatchstackProtection() and passes unscreened, while the "protection is unavailable" warning prints once. We saw this in production logs.

What fixed it for us:

  1. getProtection() returns the shared promise itself (not async). When getPatchstackProtection()'s await fails, it clears _protection if it is still the same promise, then builds once more inside the current request before failing open.
  2. The middleware passes the NextFetchEvent through: getPatchstackProtection((p) => event.waitUntil(p)) and fetchGuard()(request, event). The build and the guard's request-driven rule refresh then run under waitUntil.

Happy to share the exact patch or put together a minimal reproduction if useful.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions