Better Auth
Guard email-and-password sign-up with a before hook. This is the same hook Heimdal runs on its own signup.
Better Auth runs hooks.before ahead of every auth endpoint. A hook on the /sign-up/email path can check the visitor and refuse the sign-up before anything is written to your database.
Before you start
Section titled “Before you start”- A working Better Auth setup with
emailAndPasswordenabled. This guide was written against Better Auth 1.7. @better-auth/corein your dependencies, at the same version asbetter-auth. The hook importsgetIPfrom it.- Your Heimdal key in the
HEIMDAL_API_KEYenvironment variable.
1. Add the helper
Section titled “1. Add the helper”Save this next to your auth file. It is the TypeScript form of the helper from the Node.js guide, which explains each part: checkSignup calls the API with a timeout and returns null when there is no answer, and refusalFor turns an answer into a message or null.
import { isIP } from "node:net";
export type CheckResult = { block: boolean; reasons: string[]; email: { address: string; domain: string; disposable: boolean } | null; ip: { address: string; tor: boolean; vpn: boolean; proxy: boolean; bad_isp: boolean; asn: number | null; isp: string | null; } | null; custom: { matched: { list: string; kind: string; value: string }[] };};
const CHECK_URL = "https://heimdal.codebrewerz.com/api/v1/check";
/** Heimdal's answer, or `null` when the check could not be made. */export async function checkSignup(input: { ip: string | null; email: string;}): Promise<CheckResult | null> { try { const response = await fetch(CHECK_URL, { method: "POST", headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}`, "Content-Type": "application/json", }, // An address that is not valid would fail the whole request: leave it out. body: JSON.stringify({ ip: isIP(input.ip ?? "") ? input.ip : null, email: input.email, }), signal: AbortSignal.timeout(2000), }); if (!response.ok) { const { error } = await response.json(); console.error( `Heimdal ${response.status} ${error.code}: ${error.message}`, ); return null; } return await response.json(); } catch (cause) { console.error("Heimdal check failed, sign-up allowed:", cause); return null; }}
/** The message that refuses this sign-up, or `null` to let it through. */export function refusalFor(result: CheckResult | null): string | null { if (result === null) return null; if (result.email?.disposable) { return "Disposable email addresses can't be used to sign up."; } if (result.ip?.tor || result.ip?.proxy) { return "Sign-ups from this network aren't allowed. Contact support if this is a mistake."; } if (result.custom.matched.length > 0) { return "This sign-up can't be completed. Contact support if this is a mistake."; } return null;}2. Add the hook
Section titled “2. Add the hook”import { getIP } from "@better-auth/core/utils/ip";import { betterAuth } from "better-auth";import { APIError, createAuthMiddleware } from "better-auth/api";
import { checkSignup, refusalFor } from "./heimdal";
export const auth = betterAuth({ // ...the options you already have emailAndPassword: { enabled: true }, advanced: { // The header your reverse proxy puts the visitor's address in. ipAddress: { ipAddressHeaders: ["x-forwarded-for"] }, }, hooks: { before: createAuthMiddleware(async (ctx) => { if (ctx.path !== "/sign-up/email") return;
const email = ctx.body?.email; // Not a sign-up body: Better Auth's own validation refuses it next. if (typeof email !== "string") return;
const source = ctx.request ?? ctx.headers; const ip = source === undefined ? null : getIP(source, ctx.context.options);
const result = await checkSignup({ ip, email }); const refusal = refusalFor(result); if (refusal !== null) { throw new APIError("BAD_REQUEST", { message: refusal }); } }), },});A refused sign-up answers 400 with your message, and no user is created.
How it works
Section titled “How it works”ctx.pathis the auth endpoint being called. The hook returns early for everything except email sign-up, so sign-in and every other route are untouched.getIPresolves the visitor’s address the way Better Auth itself does, from the headers named inadvanced.ipAddress. It returnsnullwhen it cannot find an address it trusts, and the helper then checks the email alone.checkSignupfails open. If Heimdal does not answer within two seconds,resultisnull,refusalForreturnsnull, and the sign-up goes ahead.APIErrorthrown from abeforehook stops the request and reaches the client as written.
Get the IP address right
Section titled “Get the IP address right”getIP only trusts what you configure:
-
With no
trustedProxies, it accepts the header only when it holds exactly one address. A header with a chain of addresses givesnull. -
Behind more than one proxy, list your proxies so the chain can be read from the right:
advanced: {ipAddress: {ipAddressHeaders: ["x-forwarded-for"],trustedProxies: ["10.0.0.0/8"],},}, -
In development Better Auth falls back to a local address. Heimdal answers with no IP signals for it, which is what you want.
If sign-ups in production never show an IP signal, log ip in the hook. A null there means the header name or the trusted proxies do not match your setup, and the Tor and proxy checks are not running.
Show the message
Section titled “Show the message”The message arrives on the client as the error of the sign-up call:
const { error } = await authClient.signUp.email({ email, password, name });
if (error) { // "Disposable email addresses can't be used to sign up." showError(error.message);}What it covers
Section titled “What it covers”The hook guards email-and-password sign-up. Sign-ups that enter another way, such as a social provider, do not pass through /sign-up/email and are not checked by it.
© 2026 CodeBrewerz. All rights reserved.
