Make cron jobs and webhook endpoints fail closed in your Supabase or Lovable app

By Arif Khan, AIVolve LLC · Updated November 16, 2026

"My AI tool made a cron job and a webhook with JWT verification turned off. How do I know a stranger can't call them?"

Short answer: you test it, from your own terminal, with no secret. A cron job or a webhook can't send a user login, so these endpoints sit outside your normal protection, and the only guard is a secret that you check yourself. The common AI-written mistake is a check that only runs if a secret exists, like if (secret && header !== secret). If the secret is missing in production, the check disappears and every request gets in. "Fail closed" means the opposite: no secret configured, or the wrong one sent, and the endpoint refuses to run. Below is the 5-minute test, the fix, and code you can paste.

Why these endpoints need extra care

Most of your app's calls come from a signed-in user, and the platform can check that login for you. Cron jobs and webhooks are different, because the caller is a scheduler or another company's server.

What can go wrong when a stranger reaches a cron or webhook endpoint depends on what it does: send emails to your whole list, charge or refund, grant a plan, delete old rows, or call a paid AI API on your bill. A forged "payment succeeded" webhook that unlocks a paid plan is the classic example. We cover the Stripe version in Stripe works in test mode but not live.

The bug: a secret check that only runs when a secret exists

This is the shape to look for. It looks careful, and it works in testing because you set the secret:

// FAILS OPEN: if CRON_SECRET is not set, nothing is checked
const secret = Deno.env.get('CRON_SECRET')
if (secret && req.headers.get('x-cron-secret') !== secret) {
  return new Response('Unauthorized', { status: 401 })
}
// ...runs the job

We ran this on a local server. With the secret unset, a request with no header, a wrong header and the right header all got 200. An empty secret (CRON_SECRET="") also got 200, because an empty string counts as "not set" in that if. Common ways a secret goes missing: you added it to your local .env but never to the production host; you renamed it; you copied the project to a new Supabase project or a fresh Vercel deployment; or an AI tool "fixed" a 401 by deleting the check.

Step 1: List every endpoint that a machine calls

Open your project (or ask your AI tool to list them) and write down each of these:

For each one, note: what it does if it runs, who is supposed to call it, and where its secret is checked.

Step 2: Call each one with no secret

From your own terminal, call the live URL of each endpoint with no secret and then with a wrong one:

curl -i -X POST "https://YOUR-PROJECT.supabase.co/functions/v1/YOUR-FUNCTION"
curl -i -X POST -H "x-cron-secret: wrong" "https://YOUR-PROJECT.supabase.co/functions/v1/YOUR-FUNCTION"

One warning before you run it: if the endpoint is open, this call runs the job once. Do the test against a staging copy, or at a moment when one run is harmless, or on an endpoint where you've read the code and know what it does. Don't paste a real secret into a test.

What you want to see: 401 (or 403) for both calls. A 500 with "Server not configured" is also fine, and means the secret is missing and the endpoint refused to run. A 200, or the job's normal output, means anyone can run it.

Our local results with the code in step 3 and with the buggy version above:

Secret on the server Call Buggy check Fail-closed check
Not set no header 200 (open) 500 (refused)
Not set wrong header 200 (open) 500 (refused)
Set no header 401 401
Set wrong header 401 401
Set right header 200 200

The two "Not set" rows are the ones people never test, and they are exactly where the buggy version lets everyone in.

Step 3: Make it fail closed

Put the check first, before any work, and make a missing secret an error. This version also compares the strings without stopping at the first difference, and refuses very short secrets:

const enc = new TextEncoder()

// Compares every byte instead of stopping at the first difference
function sameString(a, b) {
  const x = enc.encode(a)
  const y = enc.encode(b)
  let diff = x.length ^ y.length
  const len = Math.max(x.length, y.length)
  for (let i = 0; i < len; i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0)
  return diff === 0
}

export default async function handler(req) {
  const secret = Deno.env.get('CRON_SECRET') // process.env.CRON_SECRET in Next.js
  if (!secret || secret.length < 16) {
    console.error('CRON_SECRET is missing or too short; refusing every request')
    return new Response('Server not configured', { status: 500 })
  }
  const sent = req.headers.get('x-cron-secret') ?? ''
  if (!sameString(sent, secret)) {
    return new Response('Unauthorized', { status: 401 })
  }

  // ...only now do the work
  return Response.json({ ok: true })
}

Set the secret on your host. Generate a long random value (a password manager works) and don't reuse a key from another service:

If your schedule is a Supabase Cron job, store the secret in Supabase Vault and send it from the job, so it isn't written into the job's text. Adapted from Supabase's "Scheduling Edge Functions" page (we changed the header name; this snippet needs the pg_cron and pg_net extensions on a hosted project, so we didn't run it on our local test database):

select vault.create_secret('YOUR_LONG_RANDOM_VALUE', 'cron_secret');
select vault.create_secret('https://YOUR-PROJECT.supabase.co', 'project_url');

select cron.schedule(
  'nightly-cleanup',
  '0 3 * * *',
  $$
  select net.http_post(
    url := (select decrypted_secret from vault.decrypted_secrets where name = 'project_url') || '/functions/v1/YOUR-FUNCTION',
    headers := jsonb_build_object(
      'Content-type', 'application/json',
      'x-cron-secret', (select decrypted_secret from vault.decrypted_secrets where name = 'cron_secret')
    ),
    body := '{}'::jsonb
  ) as request_id;
  $$
);

Supabase's docs add a caution you should know about: any role that can log in to your database can read the key while the request waits, because pg_net writes the decrypted value to net.http_request_queue until it sends the request. For a solo project that is usually acceptable. If other people have database access, think about who they are.

Supabase's own recommended pattern for service-to-service calls is different: turn verify_jwt off, and have the function accept only your project's secret key with withSupabase({ auth: 'secret' }, ...). Either approach is fine. What matters is that the function refuses everyone else, and that you tested it with step 2.

Step 4: Webhooks from other companies: verify the signature, and fail closed on the secret

Stripe, GitHub, Resend, Clerk and most others sign each request with a secret you get when you create the webhook. Use the provider's own library to check the signature when there is one. The Stripe version is in our Stripe guide, including the Supabase-specific constructEventAsync detail.

For a provider that sends an HMAC-SHA256 signature of the request body in a header, the shape is the same: missing secret means refuse, read the body as raw text, compare, and only then parse it:

const enc = new TextEncoder()
const toHex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')

export default async function handler(req) {
  const secret = Deno.env.get('WEBHOOK_SECRET')
  if (!secret) return new Response('Server not configured', { status: 500 })

  const body = await req.text() // the raw body, read once, before any JSON.parse
  const sent = req.headers.get('x-signature') ?? ''
  if (!sent) return new Response('Missing signature', { status: 401 })

  const key = await crypto.subtle.importKey(
    'raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
  )
  const expected = toHex(await crypto.subtle.sign('HMAC', key, enc.encode(body)))
  if (sent.length !== expected.length) return new Response('Bad signature', { status: 401 })
  let diff = 0
  for (let i = 0; i < expected.length; i++) diff |= sent.charCodeAt(i) ^ expected.charCodeAt(i)
  if (diff !== 0) return new Response('Bad signature', { status: 401 })

  const event = JSON.parse(body) // only parse after the signature passed
  return Response.json({ received: event.type })
}

Your provider's header name and signature format will differ (many add a timestamp to stop replays, so read their docs first). The structure is what to keep. We tested six cases against this code: secret not set, no signature, wrong signature, a too-short signature, a correct signature on a tampered body, and a correct signature on the right body. The first five returned 500 or 401. Only the last returned 200.

Step 5: Test again, and keep the test

Run step 2 again after every deploy that touches these files, and after you create a new Supabase project or Vercel deployment from the old one, because that's when secrets go missing. A good habit: ask your AI tool to add a test that calls the handler with the secret unset and expects a refusal.

A prompt for Lovable, Cursor or Claude Code

Audit every endpoint in this project that is called by a scheduler or an outside service: Supabase Edge Functions with verify_jwt = false, anything called by pg_cron or pg_net, Vercel cron routes, and every webhook route. Phase 1, read-only: list each endpoint, what it does when it runs, who should call it, and exactly where its secret is checked. Flag any check that only runs when a secret exists (for example "if (secret && ...)"), any endpoint with no check, and any secret I have not confirmed is set in production. Phase 2, after I approve: change each check so a missing or empty secret returns an error and never runs the job, compare secrets without stopping at the first difference, verify webhook signatures on the raw body before parsing it, and add a test that calls each handler with the secret unset and expects a refusal. Do not print or log any secret value. Do not change anything else.

FAQ

What does it mean for an endpoint to fail closed?+

It means the endpoint refuses to run whenever it can't be sure the caller is allowed. If the secret is missing, empty or wrong, it returns an error instead of doing the work. The opposite, failing open, is a check like "if a secret is set, compare it" that quietly lets everyone in when the secret isn't set.

Is it safe to turn off verify_jwt for a webhook or cron function?+

It is the normal setup for webhooks and service-to-service calls, because those callers can't send a user login. But it removes the platform's check, so your own code must do the checking: verify the provider's signature or a shared secret before doing any work, and refuse when the secret isn't configured.

Does leaving verify_jwt on protect my cron function?+

Not by itself. Supabase's docs say the check also accepts publishable and secret keys, and your publishable key is public. Treat your own secret check as the real protection, and test the endpoint with no secret.

How do I test whether my cron endpoint is open?+

Call its live URL from your terminal with curl, once with no secret and once with a wrong one. A 401, 403 or a "server not configured" error is what you want. A 200 means anyone can run it. Run the test on a staging copy or when one run is harmless, because an open endpoint will run the job.

Where should the cron secret live?+

In your host's secret store, not in your code or your repo: Supabase Edge Function secrets, or Vercel environment variables. If a database job needs to send it, keep it in Supabase Vault rather than in the job's text, and rotate it if it ever appears in a chat, a screenshot or a commit.

Want a second pair of eyes?

If you'd like a developer to look at the endpoints your AI tool created, our free X-ray takes about 2 minutes and needs no code or passwords. It points out what only looks finished, including endpoints nobody should be able to call. Get a free X-ray →

Related: Stripe works in test mode but not live · Supabase RLS for AI-built apps: the 10-minute check · Supabase anon key vs service_role key · Security audit prompts for AI-built apps

Written by Arif Khan, AIVolve LLC. VibeCoderSOS isn't affiliated with Supabase, Vercel or Stripe. Docs were checked on November 16, 2026, and the handler code was tested on a local server the same day.

Need help?

Not sure which of your endpoints a stranger could call? A free X-ray shows what your AI tool built and what only looks finished.

Get a free X-ray →