Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 5 min read

Custom Domains for Every Customer in a Next.js SaaS, with Cloudflare for SaaS

Many SaaS products eventually get the same request: "Can we use our own domain?" In EventsIQ it is not a nice-to-have. Customers put tracking links in their ads, and those links should say track.theirsite.com, not our na

Custom Domains for Every Customer in a Next.js SaaS, with Cloudflare for SaaS

Many SaaS products eventually get the same request: "Can we use our own domain?" In EventsIQ it is not a nice-to-have. Customers put tracking links in their ads, and those links should say track.theirsite.com, not our name.

This post is how I built it with Next.js and Cloudflare for SaaS. The customer adds one DNS record and never touches a certificate.

The plan in one picture

The Next.js app registers the hostname and writes the route once. Each click is then one KV read at the edge and a 302.

There are two halves:

  1. The Next.js app does the slow, careful work once: it registers the hostname with Cloudflare, watches the certificate, and writes each campaign's route into Cloudflare KV.
  2. A Cloudflare Worker answers clicks. For each request it reads one KV key, replies with a 302, and queues the click to be saved afterwards.

The Next.js app is never in the path of a click. That keeps redirects fast everywhere in the world and means a busy day in the app cannot slow down anyone's ads.

Step 1: one CNAME from the customer

The customer types a subdomain, like track.theirsite.com, and adds one record at their DNS provider:

track.theirsite.com CNAME <our fallback origin>

Two checks in the form save a lot of support:

  • Only subdomains. A bare domain like theirsite.com is refused. Pointing it at us would take over their whole website.
  • Clean up what people paste. Customers paste https://track.theirsite.com/. Strip the scheme, the path and the trailing dot, and lowercase it.

Step 2: register the hostname from a server action

Cloudflare for SaaS lets you add a customer's hostname to your own zone. The customer never signs in to Cloudflare and never adds a zone of their own.

In Next.js this lives in a server action. The Cloudflare call is a plain fetch:

"use server";

export async function createCustomHostname(hostname: string) {
  const res = await fetch(
    `https://api.cloudflare.com/client/v4/zones/${process.env.CLOUDFLARE_ZONE_ID}/custom_hostnames`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        hostname,
        ssl: {
          method: "http", // Cloudflare answers the challenge itself
          type: "dv",
          settings: { min_tls_version: "1.2" },
        },
      }),
      signal: AbortSignal.timeout(10_000),
    }
  );
  const json = await res.json();
  if (!json.success) throw new Error(json.errors?.[0]?.message ?? "Cloudflare refused the hostname");
  return json.result; // keep result.id, status and ssl.status
}

Three choices in there are worth explaining.

HTTP validation, not TXT. With method: "http", the certificate authority asks for a token on the hostname itself. That request already reaches Cloudflare because of the customer's CNAME, so Cloudflare answers it. With TXT validation, the customer would need a second record at their registrar. One record is always better than two.

TLS 1.2 as the minimum. The visitors are people tapping an ad on a modern phone. Offering TLS 1.0 helps nobody and fails the security reviews some customers run.

A timeout. A call to any outside API from a server action should have one. Without it a slow response holds the request open until the platform kills it.

Also handle "already exists". If a hostname was added before and removed only on our side, Cloudflare answers with error code 1406. Look it up and reuse it rather than showing an error nobody can explain.

Step 3: show the customer where it stands

A hostname moves through a few states, and the customer should see them in plain words:

  • Waiting for DNS : Cloudflare cannot see the CNAME yet.
  • Issuing certificate : the record is right, the certificate is on its way. Usually minutes.
  • Live : ready for traffic.

Cloudflare reports the hostname status and the certificate status separately, so read both. A Check again button that re-fetches the hostname is enough. You do not need a webhook for this.

When Cloudflare no longer has a hostname (someone tidied up in the dashboard), treat it as a state to fix, not a crash. Return null from the lookup and show the customer what to do.

Step 4: write the route to KV

When a customer saves a campaign on their domain, the app writes one KV entry:

link:track.theirsite.com:spring-quote -> { v: 3, destinations: [...], campaignId: ... }

Two lessons here.

Build the key in one place. The app writes the key and the Worker reads it. If one side lowercases the hostname and the other does not, every link returns 404 and nothing throws anywhere. So both sides import the same small file that builds the key, and that file has no imports of its own, so both the Next.js build and the Worker build can use it.

Version the stored shape. The app deploys on Vercel and the Worker deploys with Wrangler, minutes apart, and old KV entries outlive both. A v field lets the Worker refuse a shape it does not understand instead of misreading it.

Step 5: the Worker answers the click

The Worker is small on purpose. Simplified, it looks like this:

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    const url = new URL(request.url);
    const key = clickRouteKey(url.hostname, url.pathname.slice(1));
    const route = parseClickRoute(await env.CAMPAIGN_ROUTES.get(key));
    if (!route) return new Response("Not found", { status: 404 });

    const clickId = crypto.randomUUID();
    const destination = pickDestination(route, request);

    // Save the click after the reply, so the visitor never waits on it.
    ctx.waitUntil(env.CLICK_EVENTS.send({ clickId, route, url: url.href }));

    return Response.redirect(withClickId(destination, clickId), 302);
  },
};

ctx.waitUntil is the key line. The redirect goes out first, and the click is handed to a queue in the background. A queue consumer then saves it and passes it to the app. If saving fails, the message comes back and is tried again. The visitor is already on the landing page.

What it costs to run

  • The customer: one CNAME.
  • The Next.js app: a server action, a status screen and a KV write per campaign.
  • Each click: one KV read and one queue message at the edge.

Takeaways

  • Keep the Next.js app out of the hot path. Let it manage hostnames and routes, and let an edge Worker answer requests.
  • Use Cloudflare for SaaS with HTTP validation, so the customer adds exactly one record.
  • Show hostname and certificate status in plain words, with a Check again button.
  • Build shared keys in one import-free file, and version anything stored in KV.
  • Reply first, save later, with waitUntil and a queue.

I wrote more about what happens on each click in transparent click tracking with a custom domain.

Let's Work Together

If you need custom domains in your SaaS, contact me here: LinkedIn

Originally published at www.hassaanistic.com/blogs/nextjs-custom-domains-cloudflare-for-saas.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.