Workers - Reject redirects in Workers fetch requests
Cloudflare Workers now supports redirect: "error" in fetch() and Request, completing support for all three redirect modes defined by the WHATWG Fetch Standard ↗︎: follow, manual, and error.
When the server responds with a redirect status (301, 302, 303, 307, or 308), fetch() with redirect: "error" rejects with a TypeError without contacting the redirect destination. It rejects even if the response has no Location header. Non-redirect 3xx responses, such as 304 Not Modified, resolve normally.
Use redirect: "error" to:
Protect credentials and secrets: Fail closed on OAuth token exchanges, signed webhooks, and API calls carrying sensitive headers (such as Cookie, X-API-Key, or Authorization) so redirects cannot forward headers to another destination.
Prevent server-side request forgery (SSRF) redirect hops: After you validate a user-supplied URL, block redirects to unvalidated hosts. This applies to webhook targets, link previews, and feed fetchers.
Enforce strict API contracts: Catch unexpected redirects (such as an upstream API redirecting to an HTML sign-in page) immediately instead of following them, consuming extra subrequests, and failing later during response parsing.
Share code across runtimes: Use the same redirect: "error" option in Workers and browsers when your code needs to reject redirects.
src/index.jsjsexport default {
async fetch(request, env) {
try {
const response = await fetch("https://api.example.com/v1/token", {
method: "POST",
headers: {
"X-API-Key": env.API_KEY,
},
redirect: "error",
});
return response;
} catch {
return new Response(
"Upstream request failed or returned an unexpected redirect",
{
status: 502,
},
);
}
},
};src/index.tstsexport default {
async fetch(request, env): Promise {
try {
const response = await fetch("https://api.example.com/v1/token", {
method: "POST",
headers: {
"X-API-Key": env.API_KEY,
},
redirect: "error",
});
return response;
} catch {
return new Response(
"Upstream request failed or returned an unexpected redirect",
{
status: 502,
},
);
}
},
} satisfies ExportedHandler;
This mode is enabled by default for Workers with a compatibility date of 2026-12-22 or later. To opt in on an earlier compatibility date, add the fetch_redirect_error compatibility flag:
{
"$schema": "./node_modules/wrangler/config-schema.json",
"compatibility_flags": [
"fetch_redirect_error"
]
}compatibility_flags = ["fetch_redirect_error"]
For compatibility dates on or after 2026-12-22, add no_fetch_redirect_error to opt out. If you pass a URL to fetch() or new Request(), the default is follow. If you pass an existing Request, both use its redirect mode unless you override it. Incoming requests use manual.
For more information, refer to Redirect handling and the fetch_redirect_error compatibility flag.