Run Background Jobs

Run code on a schedule, like a daily signup digest or a nightly re-index, using a tiny Cloudflare Worker that calls a protected endpoint in your app.

Sooner or later your app needs to do something when nobody is clicking anything: email you yesterday’s signups, re-index your docs, expire old trials, send a weekly summary. Those are background jobs, and the simplest reliable way to run them is a timer that calls your own code.

This guide splits the work in two. Your Astro app gets a protected endpoint that does the job. A small Cloudflare Worker with a Cron Trigger calls that endpoint on a schedule. The Worker holds no business logic, so every job lives in one codebase and can also be run by hand.

The example job is a daily digest: every morning, email the founder a list of yesterday’s waitlist signups. It reuses the table from Build a Waitlist Page and the sendEmail() helper from Send Transactional Email.

What you’ll have at the end

  • A /api/jobs/daily-digest endpoint that only accepts requests carrying a secret.
  • A Cloudflare Worker that calls it every day at 08:00 UTC.
  • A job that is safe to run twice: a retry or a manual re-run never sends a second digest.
  • A way to trigger the schedule locally and see failures in production.

Before you start

  • The project from Build a Waitlist Page (a waitlist table in Supabase), or any Astro app with a server adapter.
  • src/lib/email.ts and src/lib/templates.ts from Send Transactional Email.
  • A free Cloudflare account → https://dash.cloudflare.com.

Step 1: Why a Worker, and not the host’s own cron

Some hosts have a cron feature, some don’t, and each one works differently. A Cloudflare Worker with a Cron Trigger works the same way whether your app is on Cloudflare Pages, Vercel, or a VPS, and it costs nothing at this scale. If you move hosts later, you change one URL.

Cloudflare Pages projects can’t have Cron Triggers. Even if your app is on Pages, the schedule needs a separate Worker. That is the Worker you build in Step 4.


Step 2: Add the secrets

The job reads the waitlist, which the public anon key can’t do (that was the point of the RLS policy). It needs the service role key. Add to .env:

SUPABASE_URL=https://abcd1234.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
CRON_SECRET=paste-a-long-random-string-here
DIGEST_TO=you@yourdomain.com

Generate the secret with:

openssl rand -hex 32

The service role key bypasses Row Level Security. It must only ever be used in server code like this endpoint. Never give it a PUBLIC_ prefix, never import it into a page script, and never log it.


Step 3: The job endpoint

First add a digest template to src/lib/templates.ts (it uses the esc and layout helpers already in that file):

export function digestEmail(day: string, emails: string[]): Email {
  const rows = emails.map((e) => `<li>${esc(e)}</li>`).join("");
  return {
    subject: `${emails.length} new signup${emails.length === 1 ? "" : "s"} on ${day}`,
    html: layout(`
      <h1 style="font-size:20px;margin:0 0 12px">Signups for ${esc(day)}</h1>
      ${emails.length ? `<ol>${rows}</ol>` : "<p>No new signups.</p>"}`),
    text: `Signups for ${day}:\n\n${emails.join("\n") || "No new signups."}`,
  };
}

Then create src/pages/api/jobs/daily-digest.ts:

import type { APIRoute } from "astro";
import { createClient } from "@supabase/supabase-js";
import { sendEmail } from "../../../lib/email";
import { digestEmail } from "../../../lib/templates";

export const prerender = false;

export const POST: APIRoute = async ({ request }) => {
  // 1. Only the scheduler may call this.
  const secret = import.meta.env.CRON_SECRET;
  if (!secret || request.headers.get("authorization") !== `Bearer ${secret}`) {
    return new Response("Unauthorized", { status: 401 });
  }

  // 2. Work on a fixed window: all of yesterday, in UTC. A run at 08:00 or a late
  //    retry at 11:00 covers exactly the same rows.
  const today = new Date();
  today.setUTCHours(0, 0, 0, 0);
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
  const day = yesterday.toISOString().slice(0, 10); // e.g. "2026-11-18"

  const supabase = createClient(
    import.meta.env.SUPABASE_URL,
    import.meta.env.SUPABASE_SERVICE_ROLE_KEY,
    { auth: { persistSession: false } },
  );

  const { data, error } = await supabase
    .from("waitlist")
    .select("email")
    .gte("created_at", yesterday.toISOString())
    .lt("created_at", today.toISOString())
    .order("created_at");

  if (error) {
    console.error("digest query failed:", error);
    return new Response("Query failed", { status: 500 });
  }

  // 3. One digest per day, however many times this runs.
  const sent = await sendEmail(
    import.meta.env.DIGEST_TO,
    digestEmail(day, data.map((r) => r.email)),
    { idempotencyKey: `digest/${day}` },
  );

  return sent
    ? Response.json({ ok: true, day, count: data.length })
    : new Response("Email failed", { status: 502 });
};

Three decisions in this code are worth copying into every job you write:

  • Check that the secret exists before comparing. If CRON_SECRET is missing in production, a naive check compares against "Bearer undefined", and anyone who sends that header gets in.
  • Use a fixed time window, not “the last 24 hours”. A job that runs late or twice would otherwise skip or repeat rows.
  • Make the side effect idempotent. The key digest/<date> means a retry is harmless.

Test it with the dev server running:

curl -X POST http://localhost:4321/api/jobs/daily-digest \
  -H "Authorization: Bearer $(grep CRON_SECRET .env | cut -d= -f2)"

You should get {"ok":true,...} and an email. Run it again: same response, no second email. Leave off the header and you get a 401.


Step 4: The scheduler Worker

In a new folder outside your app:

npm create cloudflare@latest digest-cron

Pick Hello World example, Worker only, TypeScript, and say no to deploying for now. Replace wrangler.jsonc (or wrangler.toml) with:

name = "digest-cron"
main = "src/index.ts"
compatibility_date = "2026-11-01"

[vars]
APP_URL = "https://yourdomain.com"

[triggers]
crons = ["0 8 * * *"] # 08:00 UTC every day

And src/index.ts with:

interface Env {
  APP_URL: string;
  CRON_SECRET: string;
}

// Which endpoint each schedule calls. Add a line per job.
const JOBS: Record<string, string> = {
  "0 8 * * *": "/api/jobs/daily-digest",
};

export default {
  async scheduled(controller: ScheduledController, env: Env): Promise<void> {
    const path = JOBS[controller.cron];
    if (!path) throw new Error(`No job for schedule ${controller.cron}`);

    const res = await fetch(env.APP_URL + path, {
      method: "POST",
      headers: { Authorization: `Bearer ${env.CRON_SECRET}` },
    });

    // Throwing marks this run as failed in the Cloudflare dashboard.
    if (!res.ok) throw new Error(`${path} returned ${res.status}: ${await res.text()}`);
    console.log(path, await res.text());
  },
};

Cron schedules run in UTC. 0 8 * * * is 08:00 UTC, which is 13:30 in India and 03:00 in New York (EST). Convert before you pick a time.


Step 5: Test the schedule locally

Put the local values in digest-cron/.dev.vars (gitignored by the template):

APP_URL=http://localhost:4321
CRON_SECRET=the-same-value-as-in-your-app

With your Astro dev server still running, start the Worker in test mode and fire the schedule by hand:

npx wrangler dev --test-scheduled
# in another terminal:
curl "http://localhost:8787/__scheduled?cron=0+8+*+*+*"

The Worker terminal logs the endpoint’s response, and the digest arrives (or is skipped as a duplicate if you already sent today’s in Step 3).


Step 6: Deploy both halves

  1. App: add SUPABASE_SERVICE_ROLE_KEY, CRON_SECRET, and DIGEST_TO to your host’s environment variables, then deploy (with Ship It, that’s a git push).
  2. Worker: store the secret and deploy:
cd digest-cron
npx wrangler secret put CRON_SECRET   # paste the same value
npx wrangler deploy

Wrangler prints the schedule it registered. In the Cloudflare dashboard, open the Worker → Settings → Triggers to confirm it, and Logs to see each run once it fires.


You now have

A scheduled job that runs every morning, can’t be called by strangers, and can’t send a duplicate. Adding a second job takes one new endpoint and one line each in crons and JOBS.


Troubleshooting

  • Every run returns 401 → CRON_SECRET differs between the Worker and the app, or the app’s copy isn’t set in production. Re-run wrangler secret put and check the host.
  • Endpoint works with curl but returns 404 from the Worker → APP_URL has a typo or a trailing slash, producing //api/....
  • Query returns nothing but rows exist → you’re using the anon key, which RLS blocks from reading. Use the service role key for this endpoint.
  • Digest arrives at the wrong hour → the schedule is UTC. Adjust the cron expression.
  • A job runs longer than a minute or two → don’t do heavy work inside one HTTP request. Split it into batches, or move it to a queue.