How-to: Add a Background Job
When the HUD needs a new heartbeat—say, refreshing a partner feed or pruning analytics—Supabase Edge Functions + Vercel Cron is our go-to combo. Here’s the recipe.
Goal
Create a function that runs every 30 minutes, responds with { ok: true }, and gives you room to expand later.
Steps
- Scaffold the Edge Function.
supabase functions new hello-job
- Implement the worker. Start simple: return a JSON heartbeat. You can bolt on DB writes later.
// supabase/functions/hello-job/index.ts
import 'jsr:@supabase/functions-js/edge-runtime.d.ts';
Deno.serve(() =>
new Response(
JSON.stringify({ ok: true, at: new Date().toISOString() }),
{ headers: { 'Content-Type': 'application/json' } },
),
);
- Deploy it.
supabase functions deploy hello-job
- Expose a cron trigger via Next.js so Vercel can call it securely.
// web/src/app/api/cron/hello/route.ts
export async function GET() {
const url = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/hello-job`;
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}`,
'Content-Type': 'application/json',
},
});
return Response.json({ ok: res.ok, payload: await res.json().catch(() => null) });
}
- Schedule it in Vercel.
- Path:
/api/cron/hello - Cron expression:
*/30 * * * * - Headers:
x-cron-secret: <CRON_SECRET>to match the other cron endpoints.
- Path:
Expected output
{"ok":true,"payload":{"ok":true,"at":"2025-09-23T12:34:56.789Z"}}
Pitfalls
- Always guard cron routes with
CRON_SECRET. Without it, anyone can hammer your background jobs. - Keep the service-role key server-side; never leak it into client bundles or logs.
Time estimate
10–15 minutes. Most of the time is clicking around Vercel’s cron UI.