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.
validateUserInfoneeds version 1.7 or later; the database hook works in earlier versions too. - A Qelka API key in the
QELKA_API_KEYenvironment variable of your server. Ask_test_key returns simulated results and never spends credits: see Test mode. A restricted key limited toemailandipis enough.
Steps
1. The lookup helper
Save as lib/signup-check.ts:
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:
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:
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
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.
Related
Frequently asked questions
Database hook, validateUserInfo or a hooks.before middleware?
Where does the person see the error?
Will an API outage stop signups?
More in Auth & backend
All integrationsPut 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