Skip to content

Auth & backend

Block fake signups in Clerk with a user.created webhook

Verify each new Clerk user's email in a signed user.created webhook, store the verdict in metadata and ban undeliverable or disposable signups. Fails open.

Updated 2026-11-26

This recipe checks the primary email of every new Clerk user in a user.created webhook, stores the verdict in the user's private metadata, and bans accounts whose address cannot receive mail or belongs to a disposable inbox service. There is no native Qelka integration for Clerk: you add one route to your app.

Clerk does not run custom code before it creates a user, as far as we know. Its webhooks are asynchronous, and its built-in protections are switches it maintains. So the account exists for a few seconds before the check lands. Banning it then is enough: Clerk documents that a ban revokes all of the user's sessions and stops them from signing in again.

What you need

  • A Clerk application and a Next.js App Router project using @clerk/nextjs, with CLERK_SECRET_KEY set. Other frameworks can use verifyWebhook from @clerk/backend/webhooks, which takes a standard Request.
  • A Qelka API key in the QELKA_API_KEY environment variable. A sk_test_ key returns simulated results and never spends credits: see Test mode. A restricted key limited to email and ip is enough for this recipe.
  • Optional but recommended: Clerk's Block disposable email addresses protection, on the Protections page of the Clerk Dashboard. Clerk lists it as included on every plan; check yours.

Steps

1. Create the webhook endpoint in Clerk

In the Clerk Dashboard, open the Webhooks page and select Add Endpoint. Enter your route's URL, such as https://your-app.example/api/webhooks/clerk. Under Subscribe to events, select user.created, then Create. Copy the endpoint's Signing Secret.

Add both secrets to your environment, never to source code:

bash
CLERK_WEBHOOK_SIGNING_SECRET=whsec_your_signing_secret
QELKA_API_KEY=sk_test_your_key

verifyWebhook reads CLERK_WEBHOOK_SIGNING_SECRET by default. To receive events on your machine, Clerk's own webhook guide uses an ngrok tunnel.

2. Keep the route public

Clerk calls the route without a session: the signature is the authentication. clerkMiddleware() protects no route by default, but if you added protection rules, exclude /api/webhooks(.*) from them.

3. A shared lookup helper

Save as lib/signup-check.ts. It calls the API with a timeout and tells the caller whether a failure is worth retrying:

typescript
export type EmailResult = {
  status: string
  reason: string
  did_you_mean: string | null
  checks: { disposable: boolean }
}

export type IpResult = {
  risk: { level: string }
  flags: { tor: boolean }
}

export type Lookup<T> = { ok: true; data: T } | { ok: false; error: string; retryable: boolean }

export async function lookup<T>(path: string, body: Record<string, unknown>): Promise<Lookup<T>> {
  let response: Response
  try {
    response = await fetch(`https://api.qelka.com/v1${path}`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.QELKA_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(8000),
    })
  } catch {
    console.warn(`${path} check failed: unreachable`)
    return { ok: false, error: 'unreachable', retryable: true }
  }
  if (response.ok) return { ok: true, data: (await response.json()) as T }
  const failure = await response.json().catch(() => null)
  const error = failure?.error?.type ?? `http_${response.status}`
  console.warn(`${path} check failed: ${error} request ${response.headers.get('X-Request-Id')}`)
  return { ok: false, error, retryable: [429, 500, 502, 503].includes(response.status) }
}

4. The webhook route

Save as app/api/webhooks/clerk/route.ts:

typescript
import { clerkClient } from '@clerk/nextjs/server'
import { verifyWebhook } from '@clerk/nextjs/webhooks'
import type { NextRequest } from 'next/server'
import { lookup, type EmailResult } from '@/lib/signup-check'

export async function POST(req: NextRequest) {
  let evt
  try {
    evt = await verifyWebhook(req)
  } catch {
    return new Response('Invalid signature', { status: 400 })
  }
  if (evt.type !== 'user.created') return new Response('Ignored', { status: 200 })

  const user = evt.data
  const email = user.email_addresses.find((address) => address.id === user.primary_email_address_id)?.email_address
  if (!email) return new Response('No email', { status: 200 })

  const check = await lookup<EmailResult>('/email', { email, mode: 'fast' })
  if (!check.ok && check.retryable) return new Response('Retry later', { status: 503 })

  const emailCheck = check.ok
    ? { status: check.data.status, reason: check.data.reason, disposable: check.data.checks.disposable }
    : { status: 'unchecked', reason: check.error, disposable: false }

  const client = await clerkClient()
  await client.users.updateUserMetadata(user.id, {
    privateMetadata: { emailCheck: { ...emailCheck, checkedAt: new Date().toISOString() } },
  })

  if (emailCheck.status === 'undeliverable' || emailCheck.disposable) {
    await client.users.banUser(user.id)
  }

  return new Response('OK', { status: 200 })
}

The primary address is the entry of email_addresses whose id matches primary_email_address_id; do not take the first entry. mode: 'fast' runs the syntax, DNS and list checks and skips the mailbox check, so the route answers quickly and never waits on someone else's mail server. Fast mode is enough to catch typos, dead domains and disposable inboxes. See the email reference.

updateUserMetadata merges into the existing metadata. Private metadata is readable and writable from the Backend API only, so the user cannot change their own verdict. Use publicMetadata instead if your frontend must read it.

5. What the route does with each answer

Result Meaning What the route does
undeliverable Bad syntax, or a domain that does not exist or takes no mail Stores the verdict and bans the user
risky, reason disposable A disposable inbox service Stores the verdict and bans the user
risky, other reasons A catch-all domain or a full mailbox Stores the verdict, keeps the user
unknown In fast mode, usually smtp_not_checked: nothing wrong was found Stores the verdict, keeps the user
unchecked The key, the balance or the request had a problem Stores it, keeps the user, logs the error type

Never ban on unknown: it means the checks could not conclude, not that the address is bad. If you would rather review than ban, drop the banUser call and filter users on privateMetadata.emailCheck in your back office. To free the address for a new signup instead, deleteUser removes the account entirely.

If your instance makes people verify their email at sign-up, an address that cannot receive mail rarely gets this far. The webhook then matters most for disposable inboxes, which do receive mail, and for any path where Clerk does not send a code.

6. Test it

Clerk treats any address with the +clerk_test subaddress as a test address in Test mode, which is on by default for development instances: no email is sent and the code 424242 verifies it. A Qelka test key ignores a +tag, so:

  • disposable+clerk_test@example.com signs up, then gets banned within seconds;
  • nomx+clerk_test@example.com is undeliverable (domain_no_mx) and gets banned;
  • jane+clerk_test@example.com is unknown with smtp_not_checked and stays.

Open each user in the Clerk Dashboard to see the metadata and the ban.

Check before Clerk creates the user

If you build a custom sign-up flow with Clerk's useSignUp, your form can call your own route before signUp.create and show the problem next to the email field, with the typo suggestion. That route sees the request, so it can also look up the IP address and flag Tor or high-risk networks:

typescript
import { lookup, type EmailResult, type IpResult } from '@/lib/signup-check'

export async function POST(request: Request) {
  const { email } = await request.json()
  const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
  const [emailCheck, ipCheck] = await Promise.all([
    lookup<EmailResult>('/email', { email, mode: 'fast' }),
    ip ? lookup<IpResult>('/ip', { ip }) : Promise.resolve(null),
  ])

  const result = emailCheck.ok ? emailCheck.data : null
  const review = ipCheck?.ok === true && (ipCheck.data.risk.level === 'high' || ipCheck.data.flags.tor)
  if (result?.status === 'undeliverable') {
    const message = result.did_you_mean ? `Did you mean ${result.did_you_mean}?` : 'This address cannot receive mail.'
    return Response.json({ ok: false, message, review })
  }
  if (result?.checks.disposable) {
    return Response.json({ ok: false, message: 'Please use a permanent email address.', review })
  }
  return Response.json({ ok: true, message: null, review })
}

Save it as app/api/signup-check/route.ts. Any failure answers ok: true, so the form never blocks on the API. Treat review as a reason for extra friction, not a refusal: many people use a VPN for privacy. Keep the webhook in place: this route improves the experience, the webhook enforces the rule. Read the client IP from the header your host sets; see Flag VPN and data center traffic.

Handle errors and rate limits

Nothing is billed on errors. Timeouts, 429, 500, 502 and 503 make the webhook answer 503, and Clerk retries the event; a pre-check failure simply lets the form continue. 401, 402 and 403 mean a wrong key, an empty balance or a restricted key: they are stored as unchecked with the error type, so alert on them. If Clerk delivers the same event again, the repeated check spends one more credit and leaves the same verdict. A key allows 200 requests per 10 seconds, and each email check costs 1 credit. To check users who signed up before the webhook existed, export them and run a bulk file check. See Errors and Rate limits.

Frequently asked questions

Can I stop a Clerk signup before the account is created?
Not with your own code on Clerk's hosted sign-up, as far as we know: Clerk's protections are preset switches it maintains, and its webhooks fire after the user exists. The only earlier point is a custom sign-up flow that calls your server before signUp.create, and a bot can call Clerk directly and skip it. That is why the webhook is the rule that always runs.
Should I also turn on Clerk's own disposable email protection?
Yes. Clerk documents Block disposable email addresses as included on every plan and off by default, and it refuses those domains during sign-up itself. The webhook adds what that switch does not: domains that cannot receive mail, typo suggestions, a verdict stored on every user, and the same rules you apply on your other signup paths.
What happens if the API is down when the webhook arrives?
The route answers 503 for timeouts, rate limits and server errors, and Clerk retries the event until it gets a 2xx answer. The account already exists and works in the meantime, so nobody is locked out. Key and balance problems are stored as unchecked with a 200 answer instead, so they do not loop; filter users on that value and check them again later.

More in Auth & backend

All integrations

Put this check in your product

Get an API key in under a minute. 100 free credits every month, no card required.

  • 100 free credits a month
  • No card
  • Test keys spend nothing
  • Cancel any time