# 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](https://www.better-auth.com) 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

- A working Better Auth setup with `emailAndPassword` enabled. This guide was written against Better Auth 1.7.
- `@better-auth/core` in your dependencies, at the same version as `better-auth`. The hook imports `getIP` from it.
- Your Heimdal key in the `HEIMDAL_API_KEY` environment variable.

## 1. Add the helper

Save this next to your auth file. It is the TypeScript form of the helper from the [Node.js guide](https://heimdal.codebrewerz.com/docs/guides/node/), 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`.

```ts title="heimdal.ts"

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

```ts title="auth.ts"

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

- **`ctx.path`** is the auth endpoint being called. The hook returns early for everything except email sign-up, so sign-in and every other route are untouched.
- **`getIP`** resolves the visitor's address the way Better Auth itself does, from the headers named in `advanced.ipAddress`. It returns `null` when it cannot find an address it trusts, and the helper then checks the email alone.
- **`checkSignup`** fails open. If Heimdal does not answer within two seconds, `result` is `null`, `refusalFor` returns `null`, and the sign-up goes ahead.
- **`APIError`** thrown from a `before` hook stops the request and reaches the client as written.

:::note[Why not a database hook?]
`databaseHooks.user.create.before` also runs before a user is created, but it does not see the request, and an error thrown from it does not reliably reach the client as you wrote it. A `before` hook on the path has neither problem.
:::

## 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 gives `null`.
- Behind more than one proxy, list your proxies so the chain can be read from the right:

  ```ts
  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

The message arrives on the client as the error of the sign-up call:

```ts
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

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.
