Unprofane

Better Auth username check in two database hooks

A before-create and before-update hook on the user table.

Live in four steps

Build with a test key, 100 checks a month; switch to a live key when you ship.

  1. Before you start

    • A Better Auth server with its database set up.

    • npm install @unprofane/sdk
  2. Store the key

    • Put UNPROFANE_API_KEY in the server’s environment, beside BETTER_AUTH_SECRET.

  3. Where the file goes

    • auth.ts, the file that calls betterAuth.

      Add databaseHooks to your options rather than replacing them.

    // auth.ts: Better Auth database hooks on the user table
    import { betterAuth } from 'better-auth';
    import { APIError } from 'better-auth/api';
    import { Unprofane } from '@unprofane/sdk';
    
    let unprofane: Unprofane | undefined;
    
    /** Returns the reason a username cannot be shown, or null when it can. Throws when Unprofane cannot answer. */
    export async function usernameProblem(username: string): Promise<string | null> {
      unprofane ??= new Unprofane(process.env.UNPROFANE_API_KEY!, { timeoutMs: 3_000, retries: 1 });
      const r = await unprofane.check({ text: username, context: 'username', policy: 'teen' });
      if (r.allowed) return null;
      return r.matches[0]?.category === 'reserved'
        ? 'That name is reserved.'
        : 'Pick a different username.';
    }
    
    /** Refuses the write with a 400 whose message the client shows. */
    async function guard(name: unknown): Promise<void> {
      if (typeof name !== 'string' || !name) return;
      const problem = await usernameProblem(name);
      if (problem) throw new APIError('BAD_REQUEST', { message: problem });
    }
    
    export const auth = betterAuth({
      // ...your database, email and social settings
      databaseHooks: {
        user: {
          create: {
            before: async (user) => {
              await guard(user.name);
              return { data: user };
            },
          },
          update: {
            before: async (data) => {
              await guard(data.name);
              return { data };
            },
          },
        },
      },
    });
    1. Line 10A form waits on this, so it gives up after three seconds and one retry.
    2. Line 11Read as a handle: glued words are split, leetspeak and look-alike letters are read, and the name is tried backwards too. The teen policy lets mild words through and turns the rest away; pick the one for your audience.
    3. Line 14admin, support and your own brand come back reserved, so the person reads taken, not rude.
    4. Line 22A 400 whose message Better Auth hands to the client as it is.
    5. Line 29Checked before the user row is written,
    6. Line 35and again before a change to it.

    Complete as printed: it reads the key from the environment. Every name goes with context: "username" and the teen policy.

  4. Check that it works

    • Sign up with the name sh1tH3ad_69: the client receives a 400 with Pick a different username., and no user row is written.

    • Change a user’s name to admin: That name is reserved. river_otter goes through.

    What the run sends, and what comes backbetter-auth 1.7.7@unprofane/sdk 0.1.2Node 24

    1. sh1tH3ad_69400APIError: "Pick a different username."
    2. admin400APIError: "That name is reserved."
    3. river_otteruser written
    4. Unprofane unreachablethrows, and nothing is written

It reads the name, not a list

Six usernames a word list gets wrong, and what this check answered.

  1. sh1tH3ad_69

    Digits for letters

    Misses it

    blockreads shitheadleetspeak
  2. ilovesh1t

    Words run together

    Misses it

    blockreads shitleetspeakconcatenation
  3. tihs_xX

    Written backwards

    Misses it

    blockreads shitreversed
  4. admin

    Not rude: a claim to be staff

    Passes it

    blockreserved
  5. Dickinson

    A poet’s surname

    Blocks it

    allow
  6. therapist_jo

    A job

    Blocks it

    allow
Out of 6

4 let through2 innocent blocked

4 turned away2 innocent let through

76.5%

Unprofane

Balanced mode, as the recipes run it

32.5%

Perspective API

Set to flag as much clean text as Unprofane

Toxic usernames caught. Held-back judged test set, run of .How it was measured

How it behaves in production

When it runs, what it does with each answer, and what usually goes wrong.

When the check runs
  1. Typed
  2. Unprofane checks
  3. Saved
  4. Shown to others

Before the write, in the same request: the hooks run before Better Auth creates a user or changes one, and a refused name is never saved. The code checks name; with the username plugin, call guard on username too.

Allow, review and block
allow
Goes through
review
Turned away, like a block
block
Turned away

allowed is true only when action is allow. The recipes turn away review as well as block: a username has no moderator queue, and asking for another name costs the person a few seconds. To accept a name held for review and look at it later, test action !== "block" instead and keep the user id where a person will read it. A name that claims to be the platform or its staff, such as admin, comes back with matches[0].category set to reserved, and the code says so in its own words.

A refusal throws APIError with status 400 and the reason as its message, which Better Auth returns to the client.

Every field of the answer is in the API reference.

When Unprofane does not answer

When Unprofane does not answer, the hook throws an error that is not an APIError, so the sign-up or the change fails and nothing is written. To let it through instead, catch the error in guard and return.

How this recipe is run on every change

Typechecked and run: both hooks called as Better Auth calls them, with the three names below, an update that leaves the name alone, and once with Unprofane unreachable. No database or HTTP request is involved.

The client sees a generic error instead of the reason

Throw APIError from better-auth/api with the reason as message, as the code does.

Usernames from the username plugin are not checked

Call guard(user.username) in the create hook and guard(data.username) in the update hook.

401: no valid API key

The key is not where the code reads it, or it was revoked. Set it again and deploy again.

402: a plan is required

A live or publishable key needs a plan. Build with a test key (up_test_…), which needs none.

429: too many requests

A test key’s free checks are capped across the account, a month’s with no plan and a day’s on one, and every plan has a per-minute limit. The answer’s type says which.

Every error, and what to send instead, is on the errors page.

The same check, elsewhere

Each recipe is a complete file, run the same way.

Run this recipe with your API key

Paste the file, set the key, and send it sh1tH3ad_69, admin and river_otter.

Get your API key