Unprofane

Clerk username check in one webhook

A webhook on user.created and user.updated that replaces a bad username.

Your users in ClerkExample
UsersSearch
Ssh1tH3ad_69user_12345678Just now
Mmira_072 days ago
Ttomtom5 days ago

user.created/api/webhooks/clerk200

UsersSearch
Aadminuser_12345678Just now
Mmira_072 days ago
Ttomtom5 days ago

user.created/api/webhooks/clerk200

UsersSearch
Rriver_otterJust now
Mmira_072 days ago
Ttomtom5 days ago

user.created/api/webhooks/clerk200

Unprofane
blockleetspeak
Your webhook
200updateUser(id, { username: "user_12345678" })
Unprofane
blockreserved
Your webhook
200updateUser(id, { username: "user_12345678" })
Unprofane
allow
Your webhook
200no change
Try a name

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 Clerk application with usernames turned on.

    • A server route Clerk can reach over HTTPS.

      The code is a Next.js App Router route; any framework that hands you a Fetch Request runs it unchanged.

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

    • UNPROFANE_API_KEY: your Unprofane key.

    • CLERK_SECRET_KEY: from API keys in the Clerk dashboard.

    • CLERK_WEBHOOK_SIGNING_SECRET: from the endpoint you add under Webhooks, subscribed to user.created and user.updated.

      verifyWebhook reads it and refuses a request Clerk did not sign.

    • All three live in the server’s environment, never in the client bundle.

  3. Where the file goes

    • app/api/webhooks/clerk/route.ts in a Next.js app.

      The endpoint URL you give Clerk is that route on your public host.

      If clerkMiddleware protects your routes, make this one public: Clerk calls it without a session.

    // app/api/webhooks/clerk/route.ts: Clerk calls this after user.created and user.updated
    import { createClerkClient } from '@clerk/backend';
    import { verifyWebhook } from '@clerk/backend/webhooks';
    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.';
    }
    
    const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY });
    const placeholder = (id: string) => `user_${id.slice(-8)}`;
    
    export async function POST(req: Request) {
      // Refuses a request Clerk did not sign (CLERK_WEBHOOK_SIGNING_SECRET).
      const event = await verifyWebhook(req).catch(() => null);
      if (!event) return new Response('Invalid signature', { status: 400 });
      if (event.type === 'user.created' || event.type === 'user.updated') {
        const { id, username } = event.data;
        // Nothing to check: no username (an email-only sign-up), or the one this hook gave.
        if (!username || username === placeholder(id)) return new Response('ok');
        // A throw answers 500, and Clerk delivers the event again later.
        const problem = await usernameProblem(username);
        if (problem) await clerk.users.updateUser(id, { username: placeholder(id) });
      }
      return new Response('ok');
    }
    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 23Refuses any request Clerk did not sign.
    5. Line 28Skips a sign-up with no username, and the placeholder this hook gave.
    6. Line 31Renames rather than deletes: the account stays and the person picks again.

    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 username sh1tH3ad_69: a moment after the delivery, the user’s username is the placeholder.

      admin is renamed the same way.

    • Sign up as river_otter: the name stays.

    • Send the endpoint a POST without Clerk’s headers, with curl: it answers 400.

    What the run sends, and what comes back@clerk/backend 3.23.2@unprofane/sdk 0.1.2Node 24

    1. sh1tH3ad_69200updateUser(id, { username: "user_12345678" })
    2. admin200updateUser(id, { username: "user_12345678" })
    3. river_otter200no change
    4. Unprofane unreachable500throws, and Clerk delivers again

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. Saved and shown
  3. Unprofane checks
  4. Renamed when refused

After the write. Clerk saves the username first and sends the event afterwards, so the name is live until the webhook renames the user to the placeholder in the code. Tell the person and ask for another name. If a name must never appear, check it in your own form before you call Clerk (the raw HTTP recipe, on your server) and keep this webhook as the backstop.

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.

The webhook renames rather than deletes: the account stays, and the person picks a new name.

Every field of the answer is in the API reference.

When Unprofane does not answer

When Unprofane does not answer, usernameProblem throws, the route answers 500, and Clerk delivers the event again later on its own retry schedule. The name stays live until a delivery goes through.

How this recipe is run on every change

Typechecked and run: deliveries signed the way Clerk signs them and one that is not, a sign-up with no username, the hook’s own placeholder, the three names below, and once with Unprofane unreachable. Clerk’s user API is answered by a stand-in.

Every delivery answers 400

The signing secret is not this endpoint’s: copy it again from the endpoint page. A body your framework parsed or changed before verifyWebhook read it fails the check too.

Deliveries answer 401, or a redirect to sign-in

Middleware protects the route. Make it public.

No delivery reaches your machine

Clerk needs a public HTTPS address. Use a tunnel while you develop.

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