DEV Community

seller-mind
seller-mind

Posted on

Why I Moved My SaaS Backend Logic to Cloudflare Workers

When I first started building my SaaS, I treated the backend like an afterthought. I spun up a Next.js project, connected a database, and called it a day. But as I started adding features that required external API calls—like an SEO analyzer that fetches and parses live web pages—I hit a wall. Users in Europe and Asia were complaining about slow load times. I was running all my API routes in a single region, and the latency was killing the user experience. I realized that if I wanted to build a truly global product, I needed to rethink where my code was running. So I decided to build something different.

The Hidden Cost of Centralized APIs

The problem with traditional serverless functions is that they are often bound to a specific geographic region. If your origin is in us-east-1, a user in Tokyo is paying a network round-trip penalty before your code even executes. For a simple database read, this is manageable. But for an SEO tool that needs to fetch a target URL, parse the HTML, and return a JSON response, that latency compounds.

The cost of ignoring this isn't just a few extra milliseconds; it's user frustration and abandoned sessions. When your tool feels sluggish, users assume the underlying data is stale or the product is broken. I needed a way to process these requests closer to the user, without sacrificing the developer experience of the Next.js ecosystem.

Architecting the Edge

To solve this, I made a core architectural decision: move the heavy, external-facing API logic to the edge using Cloudflare Workers, while keeping the core Next.js 14+ App Router application on Vercel. This hybrid approach gives you the best of both worlds. Next.js handles the React server components, authentication via NextAuth.js, and the UI. Cloudflare Workers handle the edge-side API routes, specifically the SEO analysis tools.

Conceptually, the architecture flows like this:

  1. The user interacts with the Next.js frontend.
  2. The frontend makes a fetch request to an analysis endpoint.
  3. The request is routed to a Cloudflare Worker running at the edge.
  4. The Worker fetches the target URL, parses it locally, and returns JSON.

This keeps the Next.js serverless functions lightweight and focused on UI rendering and authentication, while the heavy lifting is pushed to the edge.

Here is the actual Cloudflare Worker code I use for the edge SEO analysis:

// Cloudflare Worker for edge SEO analysis
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    if (url.pathname !== '/api/analyze') {
      return new Response('Not found', { status: 404 });
    }

    const targetUrl = url.searchParams.get('url');
    if (!targetUrl) {
      return new Response(JSON.stringify({ error: 'Missing url' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    // Fetch target page at the edge (low latency worldwide)
    const response = await fetch(targetUrl, {
      cf: { cacheTtl: 300, cacheEverything: true },
    });
    const html = await response.text();

    // Run SEO checks (regex-based, no DOM needed)
    const title = html.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1] || '';
    const desc = html.match(/<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i)?.[1] || '';
    const h1Count = (html.match(/<h1[ >]/gi) || []).length;

    return new Response(JSON.stringify({ title, desc, h1Count }), {
      headers: { 'Content-Type': 'application/json' },
    });
  },
};
Enter fullscreen mode Exit fullscreen mode

Breaking Down the Edge Logic

There are a few key decisions in this code worth highlighting. First, notice the cf object in the fetch call. This is a Cloudflare-specific feature that allows us to cache the external response at the edge for 300 seconds. This means if multiple users check the same URL, the subsequent requests are lightning fast because the HTML is served directly from the edge cache.

Second, I am parsing the HTML with regex instead of a heavy DOM parser like jsdom. Running a full DOM parser in an edge environment can be memory-intensive and slow. By sticking to simple regex patterns, the Worker stays incredibly lightweight and executes in milliseconds.

The Trade-offs

Moving to the edge isn't a magic bullet, and it comes with trade-offs. The biggest hurdle is the runtime environment. Cloudflare Workers use the V8 engine directly, which means you don't have access to Node.js-specific APIs. You have to rely on standard Web APIs. If your existing codebase relies heavily on Node built-ins like fs or crypto (though Web Crypto is available), you will need to refactor.

It requires a mental shift from thinking about a monolithic backend to thinking about distributed edge functions. However, for read-heavy, external-fetching tasks, the performance gains are undeniable.

Practical Results and Takeaways

What worked well was the immediate drop in latency for global users. For example, a request that might take 400ms from a central server can resolve in under 50ms at the edge. The user experience for the SEO checker tool improved dramatically.

What surprised me was how little code I actually had to rewrite. Since modern JavaScript at the edge relies on standard Web APIs, the transition was mostly about changing the deployment target rather than rewriting core logic. The TypeScript-first approach also made the migration smoother, as the type safety caught API mismatches early.

If I were to do it again, I would design the edge boundaries on day one. Migrating existing routes later meant dealing with CORS headers and routing quirks that I could have avoided by planning the architecture upfront. I also integrated Stripe subscription billing with secure webhooks to ensure that access to these premium edge features is properly gated, keeping the business logic clean and separate from the edge execution.

Try It Yourself

If you want to see this edge architecture in action, I built a free SEO checker tool using this exact setup. You can test your landing pages, analyze the metadata, and see how fast edge-based analysis can be without any sign-up walls.

You can try the free SEO checker here: https://saaslaunch.dev/free-tools/seo-checker


Full disclosure: I'm the developer of SaaSLaunch. I built this because I needed it myself.

Top comments (0)