<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged cloudflare-workers</title>
<link>https://coderlegion.com/tag/cloudflare-workers</link>
<description>Powered by Question2Answer</description>
<item>
<title>Isolating Publisher Integrations in Workflows</title>
<link>https://coderlegion.com/29590/isolating-publisher-integrations-in-workflows</link>
<description>&lt;p&gt;When a content management system successfully commits a canonical article, the primary publication work is complete. However, the system often needs to distribute that article to multiple third-party platforms via external APIs. If these optional distribution calls execute within the same execution context as the primary write, they consume valuable subrequest limits and execution time. When an external destination times out or encounters rate limiting, the primary serverless invocation can fail. This leaves the system in an ambiguous state where the article exists on the primary site, but its distribution status is entirely unknown. For a related implementation, see &lt;a rel=&quot;nofollow&quot; href=&quot;https://raylabs.app/articles/managing-concurrent-git-commits-during-automated-publishing/&quot;&gt;Managing Concurrent Git Commits During Automated&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;To solve this challenge, engineers must isolate optional third-party publisher integrations from the canonical publishing path. By separating the primary database commit from the secondary distribution phase, the system guarantees that optional mirror failures never roll back the primary page. This approach protects the primary execution budget while providing a clear mechanism to manage external API rate limits and network latency.&lt;/p&gt;
&lt;h3 id=&quot;isolating-distribution-via-child-workflows&quot;&gt;Isolating Distribution via Child Workflows&lt;/h3&gt;
&lt;p&gt;The most reliable way to achieve this separation is through a parent-child workflow pattern. Once the primary article is verified and safely committed, the parent workflow triggers an asynchronous child workflow and returns a success response to the publisher. The child workflow takes ownership of the approved rendered payload and fans out requests to each enabled external destination.&lt;/p&gt;
&lt;p&gt;Consider a scenario where an article must be mirrored to two different platforms. Instead of executing these calls inline and risking a subrequest limit exhaustion, the child workflow iterates through the destinations sequentially or in a controlled batch. Below is an architectural example demonstrating how a workflow delegates the payload to an isolated publishing routine:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from &quot;cloudflare:workers&quot;

interface PublishParams {
  articleId: string;
  canonicalUrl: string;
  destinations: string[];
}

export class ContentPublishWorkflow extends WorkflowEntrypoint&amp;lt;Env, PublishParams&amp;gt; {
  async run(event: WorkflowEvent&amp;lt;PublishParams&amp;gt;, step: WorkflowStep) {
    const { articleId, canonicalUrl, destinations } = event.payload;

    const publicationResult = await step.do(&quot;commit-canonical-article&quot;, async () =&amp;gt; {
      return { status: &quot;committed&quot;, articleId, canonicalUrl };
    });

    await step.do(&quot;trigger-distribution-fanout&quot;, async () =&amp;gt; {
      return fetch(&quot;https://internal.service/distribute&quot;, {
        method: &quot;POST&quot;,
        body: JSON.stringify({ articleId, destinations })
      });
    });

    return publicationResult;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;managing-partial-states-and-completion-truthfully&quot;&gt;Managing Partial States and Completion Truthfully&lt;/h3&gt;
&lt;p&gt;A common pitfall in fan-out architectures is collapsing diverse outcomes into a single boolean success state. If one destination succeeds while another enters a moderation queue or experiences a timeout, labeling the entire batch as a failure or success hides critical operational data. For a related implementation, see &lt;a rel=&quot;nofollow&quot; href=&quot;https://raylabs.app/articles/android-viewmodel-partial-success-refresh-failure/&quot;&gt;Viewmodel Partial Success Refresh Failure&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Robust publisher isolation requires tracking and reporting explicit completion states for every destination. The child workflow should record outcomes individually, distinguishing among live publication, moderation queuing, partial failure, and explicit timeouts. Before creating a duplicate record on a destination platform, the integration should perform a canonical URL check to ensure the article has not already been published during a previous retry attempt.&lt;/p&gt;
&lt;p&gt;By treating distribution as an asynchronous, bounded secondary process, systems maintain high reliability for the canonical path without sacrificing visibility into external API behaviors.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/29590/isolating-publisher-integrations-in-workflows</guid>
<pubDate>Sat, 03 Oct 2026 05:21:56 +0000</pubDate>
</item>
<item>
<title>Safely Rejecting Redirects in Cloudflare Workers</title>
<link>https://coderlegion.com/29539/safely-rejecting-redirects-in-cloudflare-workers</link>
<description>&lt;p&gt;When writing a Cloudflare Worker that fetches remote assets from third party APIs or origin servers, an outbound request might return a 3xx redirect status code. Automatically following that redirect can bypass internal URL allowlists, leak authorization headers to unintended destinations, and compromise application security. Standard browser or Node.js fetch configurations do not always translate directly to edge runtimes. If you rely on unsupported fetch options or assume the runtime will automatically sanitize redirect hops, your application can fail silently or forward sensitive data to external hosts.&lt;/p&gt;
&lt;p&gt;This guide explains how to fetch remote assets securely in Cloudflare Workers by using manual redirect handling, validating your initial targets, and explicitly rejecting unexpected 3xx responses.&lt;/p&gt;
&lt;h3 id=&quot;the-edge-runtime-redirect-problem&quot;&gt;The Edge Runtime Redirect Problem&lt;/h3&gt;
&lt;p&gt;The Fetch API standard defines several modes for handling HTTP redirect responses, including follow, error, and manual. However, edge environments like Cloudflare Workers execute under specific constraints. When an outbound request triggers a redirect, the runtime must decide how to handle the subsequent network hop. Developers often attempt to use options that are either unsupported for outbound Worker requests or behave unexpectedly under specific compatibility dates, causing runtime exceptions before a useful response can be parsed.&lt;/p&gt;
&lt;p&gt;Furthermore, if your Worker fetches an asset on behalf of a user, following redirects blindly can lead to Server Side Request Forgery (SSRF) vulnerabilities. If an allowlist permits a safe domain, but that domain issues an HTTP 302 pointing to an internal metadata service or an untrusted external host, an automated redirect will bridge the gap. To prevent this, you must inspect the intermediate response rather than letting the runtime follow it automatically. For a related implementation, see &lt;a rel=&quot;nofollow&quot; href=&quot;https://raylabs.app/articles/managing-concurrent-git-commits-during-automated-publishing/&quot;&gt;Managing Concurrent Git Commits During Automated&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id=&quot;validating-the-initial-url&quot;&gt;Validating the Initial URL&lt;/h3&gt;
&lt;p&gt;Before initiating any outbound network call, your Worker should validate the target URL. Relying solely on string matching is often insufficient because URL parsers can interpret malformed inputs in unexpected ways. Always parse the input string using the global &lt;code&gt;URL&lt;/code&gt; constructor and check the protocol and hostname explicitly against a strict allowlist.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;function isValidTargetUrl(rawUrl) {
  try {
    const parsed = new URL(rawUrl);
    const allowedHosts = [&quot;api.trusted-domain.com&quot;, &quot;assets.trusted-domain.com&quot;];
    
    if (parsed.protocol !== &quot;https:&quot;) {
      return false;
    }
    
    if (!allowedHosts.includes(parsed.hostname)) {
      return false;
    }
    
    return true;
  } catch (error) {
    return false;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By ensuring the initial URL meets strict protocol and host requirements, you establish a secure foundation for the outbound fetch operation.&lt;/p&gt;
&lt;h3 id=&quot;implementing-manual-redirect-handling&quot;&gt;Implementing Manual Redirect Handling&lt;/h3&gt;
&lt;p&gt;To prevent the edge runtime from following redirects automatically, pass &lt;code&gt;redirect: &quot;manual&quot;&lt;/code&gt; in the options object of your &lt;code&gt;fetch&lt;/code&gt; call. When you specify manual mode, any 3xx response is returned directly to your Worker code as a standard &lt;code&gt;Response&lt;/code&gt; object instead of triggering a transparent follow sequence.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;async function secureFetchAsset(targetUrl) {
  if (!isValidTargetUrl(targetUrl)) {
    throw new Error(&quot;Target URL failed validation checks.&quot;);
  }

  const response = await fetch(targetUrl, {
    redirect: &quot;manual&quot;,
    headers: {
      &quot;User-Agent&quot;: &quot;SecureWorkerAssetFetcher/1.0&quot;
    }
  });

  if (response.status &amp;gt;= 300 &amp;amp;&amp;amp; response.status &amp;lt; 400) {
    const redirectLocation = response.headers.get(&quot;Location&quot;);
    throw new Error(`Outbound request attempted a redirect to: ${redirectLocation || &quot;unknown destination&quot;}`);
  }

  if (!response.ok) {
    throw new Error(`Upstream service returned status: ${response.status}`);
  }

  return response;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this implementation, if the upstream server responds with a 301, 302, 303, 307, or 308, the status check catches the condition immediately. The Worker aborts execution without reading the response body or forwarding sensitive headers to the &lt;code&gt;Location&lt;/code&gt; target.&lt;/p&gt;
&lt;h3 id=&quot;managing-credentials-and-sensitive-headers&quot;&gt;Managing Credentials and Sensitive Headers&lt;/h3&gt;
&lt;p&gt;When a redirect is followed automatically, runtime clients often propagate authorization headers, cookies, or custom tokens to the new destination. If an untrusted server captures a redirect, it can harvest these credentials.&lt;/p&gt;
&lt;p&gt;By keeping redirect handling in manual mode, your Worker maintains complete control over token propagation. If a legitimate business requirement ever dictates that a redirect must be followed, your code must revalidate the new &lt;code&gt;Location&lt;/code&gt; URL against your original security policy before issuing a secondary &lt;code&gt;fetch&lt;/code&gt; call.&lt;/p&gt;
&lt;h3 id=&quot;testing-your-redirect-policy&quot;&gt;Testing Your Redirect Policy&lt;/h3&gt;
&lt;p&gt;To ensure your Worker handles various network responses predictably, maintain a small test matrix covering direct successes, redirects, client errors, and invalid URLs. &lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Test Case &lt;/th&gt;&lt;th&gt;Initial URL Status &lt;/th&gt;&lt;th&gt;Expected Behavior&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Direct 200 OK &lt;/td&gt;&lt;td&gt;Valid trusted domain &lt;/td&gt;&lt;td&gt;Returns response body successfully&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;HTTP 302 Redirect &lt;/td&gt;&lt;td&gt;Trusted domain pointing elsewhere &lt;/td&gt;&lt;td&gt;Throws error and stops before following&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;HTTP 404 Not Found &lt;/td&gt;&lt;td&gt;Valid trusted domain &lt;/td&gt;&lt;td&gt;Throws upstream status error&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Disallowed Host &lt;/td&gt;&lt;td&gt;Untrusted domain &lt;/td&gt;&lt;td&gt;Throws validation error immediately&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Adding these verification checks alongside your production fetch path prevents regressions during runtime updates and ensures your edge applications maintain strict security boundaries.&lt;/p&gt;
&lt;h3 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Outbound fetch operations in edge runtimes require deliberate security controls to prevent unintended data exposure and SSRF vulnerabilities. By validating initial target URLs, configuring manual redirect policies, and explicitly inspecting 3xx status codes, you protect your infrastructure from unsafe redirects while maintaining predictable performance at the edge.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/29539/safely-rejecting-redirects-in-cloudflare-workers</guid>
<pubDate>Fri, 02 Oct 2026 12:28:25 +0000</pubDate>
</item>
</channel>
</rss>