Repository navigation
Description
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/connect0.5.83. Guard generated bynpx @patchstack/connect setup --widget, composed intomiddleware.ts(Edge runtime), plusnpx @patchstack/connect protectwrapping 15 App Router route handlers.next16.4.6 (App Router,middleware.tson the Edge runtime)@opennextjs/cloudflare1.20.18,wrangler4.166.0- Worker
compatibility_date2025-08-01, flagsnodejs_compatandglobal_fetch_strictly_public
What happened
- Deployed with the generated guard file unchanged.
- Pages and the middleware worked.
- The first signed-in request to a route handler that calls
fetch()to an external HTTPS API failed withError: Worker exceeded memory limitand a 503. Every such route failed the same way.
Reproduced locally
opennextjs-cloudflare build, thenwrangler devon the output.- Request a route handler that does an outbound
fetch(). - workerd prints
JavaScript heap out of memoryandThe Workers runtime crashed unexpectedly and is being restarted. - 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 (nonode:dnslookup,navigator.userAgent === "Cloudflare-Workers", orglobalThis.fetch.__nextPatched) and don't wrap a fetch that is already patched. - On Workers, Cloudflare's
global_fetch_strictly_publiccompatibility flag already refuses fetches to private and internal addresses.setuporprotectcould suggest it there instead of egress. protect --checkcould 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:
getProtection()returns the shared promise itself (notasync). WhengetPatchstackProtection()'s await fails, it clears_protectionif it is still the same promise, then builds once more inside the current request before failing open.- The middleware passes the
NextFetchEventthrough:getPatchstackProtection((p) => event.waitUntil(p))andfetchGuard()(request, event). The build and the guard's request-driven rule refresh then run underwaitUntil.
Happy to share the exact patch or put together a minimal reproduction if useful.
Activity