Skip to content

Auth & backend

Block fake signups in Better Auth with a database hook

Reject undeliverable and disposable emails in Better Auth's databaseHooks.user.create.before with APIError, store the verdict on the user and flag risky IPs.

Updated 2026-11-26

This recipe validates every new Better Auth user in a databaseHooks.user.create.before hook. One email check rejects addresses that cannot receive mail or belong to a disposable inbox service, and an IP lookup flags signups from high-risk networks. The verdict is stored on the user record. There is no native Qelka plugin for Better Auth: the hook is a few lines in your auth.ts.

The hook runs on your server just before the user row is written, for email and password signups as well as social and magic link ones. Throwing an APIError there stops the creation; returning { data } changes what is written.

What you need

  • A Better Auth setup with a database. validateUserInfo needs version 1.7 or later; the database hook works in earlier versions too.
  • A Qelka API key in the QELKA_API_KEY environment variable of your server. A sk_test_ key returns simulated results and never spends credits: see Test mode. A restricted key limited to email and ip is enough.

Steps

1. The lookup helper

Save as lib/signup-check.ts:

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 async function lookup<T>(path: string, body: Record<string, unknown>): Promise<T | null> {
  try {
    const 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(5000),
    })
    if (response.ok) return (await response.json()) as T
    const failure = await response.json().catch(() => null)
    const type = failure?.error?.type ?? `http_${response.status}`
    if (type !== 'unprocessable_input') {
      console.warn(`${path} check skipped: ${type} request ${response.headers.get('X-Request-Id')}`)
    }
  } catch {
    console.warn(`${path} check skipped: unreachable`)
  }
  return null
}

A 422 unprocessable_input from /ip means a private or loopback address, which is what your server sees in local development, so it is not logged as a failure.

2. The hook

In lib/auth.ts, add two server-owned fields to the user and the hook:

typescript
import { betterAuth } from 'better-auth'
import { APIError } from 'better-auth/api'
import { lookup, type EmailResult, type IpResult } from './signup-check'

export const auth = betterAuth({
  user: {
    additionalFields: {
      emailStatus: { type: 'string', required: false, input: false },
      signupReview: { type: 'boolean', required: false, defaultValue: false, input: false },
    },
  },
  databaseHooks: {
    user: {
      create: {
        before: async (user, ctx) => {
          const ip = ctx?.headers?.get('x-forwarded-for')?.split(',')[0]?.trim()
          const [email, network] = await Promise.all([
            lookup<EmailResult>('/email', { email: user.email, mode: 'fast' }),
            ip ? lookup<IpResult>('/ip', { ip }) : Promise.resolve(null),
          ])

          if (email?.status === 'undeliverable') {
            throw new APIError('BAD_REQUEST', {
              message: email.did_you_mean
                ? `This address cannot receive mail. Did you mean ${email.did_you_mean}?`
                : 'This address cannot receive mail. Please check it.',
            })
          }
          if (email?.checks.disposable) {
            throw new APIError('BAD_REQUEST', { message: 'Please sign up with a permanent email address.' })
          }

          return {
            data: {
              ...user,
              emailStatus: email ? email.status : 'unchecked',
              signupReview: network ? network.risk.level === 'high' || network.flags.tor : false,
            },
          }
        },
      },
    },
  },
})

Keep your existing database, providers and plugins in the same object. input: false stops a client from sending these fields in the sign-up body; the hook still writes them, because its returned data is what gets stored.

mode: 'fast' runs the syntax, DNS and list checks and skips the mailbox check, which waits on the recipient's mail server while the person stares at a spinner. Fast mode still catches typos, dead domains and disposable inboxes; the verification email you send afterwards proves the mailbox. See the email reference.

ctx can be null when a user is created outside a request, so the code reads the headers with optional chaining and skips the IP lookup then. Read the client address from the header your host or proxy sets: x-forwarded-for is only trustworthy behind a proxy that overwrites it. Flag VPN and data center traffic covers this.

3. Update the schema

The two fields need columns. Generate or apply the schema change with the Better Auth CLI:

bash
npx auth@latest generate
npx auth@latest migrate

generate writes the schema for your ORM (Prisma, Drizzle) or an SQL file; migrate applies it directly with the built-in Kysely adapter. Use the one that matches your setup.

4. Show the error in the form

typescript
import { authClient } from '@/lib/auth-client'

export async function submitSignup(name: string, email: string, password: string) {
  const { error } = await authClient.signUp.email({ name, email, password })
  if (error) return { field: 'email', message: error.message ?? 'Sign-up failed. Please try again.' }
  return { field: null, message: null }
}

5. What each answer does

Result Meaning Hook
Email undeliverable Bad syntax, or a domain that does not exist or takes no mail Rejects, with did_you_mean when there is one
Email risky, reason disposable A disposable inbox service Rejects
Email risky, other reasons A catch-all domain or a full mailbox Creates the user, emailStatus: risky
Email unknown In fast mode, smtp_not_checked: nothing wrong was found Creates the user
No answer API unreachable, key or balance problem Creates the user, emailStatus: unchecked
IP high risk or Tor Anonymizing or abusive network Creates the user, signupReview: true

Never reject on unknown or on the IP alone. Use signupReview in your app to ask for an extra step before costly actions, such as a verified email before a free trial starts. To flag disposable inboxes instead of refusing them, replace that throw with emailStatus: 'disposable' in the returned data; Block disposable email signups helps you choose.

6. Test it

With a test key, sign up with disposable@example.com (rejected), nomx@example.com (rejected as domain_no_mx) and jane@example.com (created, emailStatus: unknown, since fast mode skips the mailbox check). Send x-forwarded-for: 198.51.100.200 from a local test client to see signupReview set: a test key maps that address to a Tor exit.

Only rejecting: validateUserInfo

If you never store a verdict, Better Auth 1.7 and later document user.validateUserInfo as the gate for accepting or rejecting an identity, before user creation and account linking, for every sign-in method. Run the same email check there when source.action is create-user, and return { error: 'email_rejected', errorDescription: 'Please use a permanent email address.' } to refuse. Better Auth returns a 403 for programmatic flows and sends browser flows to your error URL. Keep errorDescription free of anything sensitive: it reaches the client.

Handle errors and rate limits

Nothing is billed on errors. The helper never retries inside a signup: a 429 or a 5xx answer becomes unchecked, which keeps sign-up fast. 401, 402 and 403 mean a wrong key, an empty balance or a restricted key: alert on those log lines. Better Auth notes that on MongoDB with transactions, a before hook can run more than once for one operation; each extra run is one more check. A key allows 200 requests per 10 seconds, and a signup costs 1 credit for the email plus 1 for the IP. Rate limit your sign-up endpoint too, so a bot cannot spend your credits. See Errors and Rate limits.

Frequently asked questions

Database hook, validateUserInfo or a hooks.before middleware?
The database hook runs whenever Better Auth creates a user, whatever the sign-in method, and it can both reject and write fields, so one API call covers both. Since version 1.7, user.validateUserInfo is Better Auth's documented accept-or-reject gate across every method: use it if you only reject and never store a verdict. A hooks.before middleware on /sign-up/email covers the email and password endpoint only.
Where does the person see the error?
The APIError message comes back as the error of the sign-up request. With the client, authClient.signUp.email resolves with error.message set to it, so show it next to the email field. The message includes the typo suggestion when the API has one.
Will an API outage stop signups?
No. The lookup helper returns null on a timeout, a network error or any error response, and the hook then creates the user with emailStatus set to unchecked. Query those users later to check them again, and watch the log lines, which carry the error type and the request id.

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