Skip to Content
better-auth-plugins

Blocklist

Block disallowed emails, usernames, organization and team names, passwords, and IP addresses.

The blocklist plugin stops disallowed values whenever they are created or changed: disposable email addresses, reserved usernames such as admin, and organization or team names you don't want. Rules come from the plugin options, from ready-made lists, and from a database table that admins can change at runtime.

  • Checks every user creation and update, not only email sign-up: OAuth, magic link, email OTP, the admin plugin, and email changes.
  • Normalizes before matching, so ADMIN, admin, and аdmin with a Cyrillic "а" are all caught.
  • Ships opt-in lists of disposable email domains and reserved usernames.
  • Blocks weak passwords, including ones that contain the user's email, username, or the app name, and sign-ups and sign-ins from IP addresses, ranges, or countries you choose.

Installation

Install the package

npm install @checodo/better-auth-blocklist

Add the plugin to your auth config

auth.ts
import { betterAuth } from "better-auth";
import { blocklist } from "@checodo/better-auth-blocklist";

export const auth = betterAuth({
  plugins: [
    blocklist({
      email: {
        domains: ["mailinator.com"],
        addresses: ["spam@example.org"],
      },
      username: {
        values: ["admin", "root"],
      },
    }),
  ],
});

Migrate the database

The plugin adds a blocklistRule table for rules managed at runtime (see Schema).

npx auth@latest migrate

Add the client plugin

Only needed to manage rules from the client.

auth-client.ts
import { createAuthClient } from "better-auth/client";
import { blocklistClient } from "@checodo/better-auth-blocklist/client";

export const authClient = createAuthClient({
  plugins: [blocklistClient()],
});

Usage

Configure each target you want to guard. Targets you leave out have no static rules, but rules added at runtime (see Managing rules at runtime) still apply to them unless you set useDatabase: false on the target.

auth.ts
blocklist({
  email: {
    domains: ["mailinator.com"], // also blocks sub.mailinator.com
    addresses: ["spam@example.org"], // also blocks spam+tag@example.org
    allow: ["ceo@mailinator.com"], // always allowed
  },
  username: {
    values: ["admin", { value: "^support_", type: "regex" }],
  },
  organization: {
    values: ["billing", { value: "official", type: "contains" }],
  },
  team: {
    values: ["everyone"],
  },
});

A blocked value fails the request with a 400:

{ "code": "EMAIL_NOT_ALLOWED", "message": "This email address is not allowed" }

What is checked

TargetChecked onRequires
emailEvery user creation and update, /change-email and /email-otp/request-email-change before a verification email or code is sent, the waitlist plugin's /waitlist/join and /waitlist/create-invite, and the organization plugin's /organization/invite-member (before the invitation email is sent)-
usernameUsername and display username on every user creation and update, and /is-username-availableusername plugin
organizationName and slug on /organization/create and /organization/update, and slug on /organization/check-slugorganization plugin
teamName on /organization/create-team and /organization/update-team, and the default team's name on /organization/createorganization plugin, with teams
passwordNew passwords on /sign-up/email, /change-password, /set-password, /reset-password, /email-otp/reset-password, /phone-number/reset-password, /admin/create-user, and /admin/set-user-password (see Passwords)-
ipThe client IP address and country on every sign-up and sign-in (see IP addresses and countries)-

Emails and usernames are checked in database hooks, so every way a user is created or updated is covered, including OAuth sign-ups and admin actions. On updates, only emails and usernames that actually change are checked, so a rule added later doesn't lock out existing users, for example when an OAuth sign-in writes their unchanged email back. Display usernames aren't unique, so they are checked whenever an update sets them, changed or not: a user whose display username matches a newer rule has to pick another one the next time they save it. With teams enabled, the organization plugin creates a default team named after each new organization, so that name must also pass the team rules.

Availability checks

/is-username-available and /organization/check-slug answer a blocked value with the same error as the real request, so a form can show it while the user types. They don't call onBlocked: nothing is created, and they run on every keystroke.

Passwords

password rules block new passwords, wherever one is set: sign-up, change, reset (by link, email OTP, or phone OTP), and when an admin creates a user or sets a password. Passwords are never checked on sign-in, so a rule added later doesn't lock anyone out.

auth.ts
blocklist({
  password: {
    values: [
      "password123",
      { value: "qwerty", type: "contains" },
      { value: "^\\d+$", type: "regex", reason: "Digits only" },
    ],
  },
});

Passwords are compared after normalization and with leetspeak folded, so the rule password123 also blocks P@ssw0rd123 and pa55word123. regex rules run on the normalized password before folding, so \d still means a digit.

With the password option set, a built-in context check also blocks passwords that contain the user's email address (its local part, without a +tag), username, or the app name (appName, when you set one), each whole and split into words, ignoring words shorter than 4 characters. jane.doe@example.com can't use JaneDoe2024 or doe-r4y-jane. Turn it off with checkContext: false.

NIST SP 800-63B-4

NIST's password blocklist (§3.1.1.2) compares the entire password against commonly used, expected, and compromised passwords, including context-specific words such as the service name and the username. Use exact rules (the default) for that list. The context check and prefix, suffix, contains, and regex rules compare parts of a password: they are stricter policies of your own, not the comparison NIST requires. See Compliance.

A password is checked when better-auth hashes it, so after its own length checks and after a reset token or OTP is verified: the rules can't be probed without one, and a blocked attempt doesn't use up the token.

Passwords are never passed on

onBlocked and the audit log get "[redacted]" as the value, never the password, and as the value of the rule that matched: an exact rule is the password itself, a contains rule part of it. The rule's type and reason are kept. For the context check, the rule's value says where the word came from: "[email]", "[username]", or "[appName]".

With haveIBeenPwned

The rules complement better-auth's haveIBeenPwned plugin, which rejects passwords found in data breaches. Both check the same endpoints (the blocklist also checks /set-password) and can be used together.

IP addresses and countries

ip rules block sign-ups and sign-ins from addresses, CIDR ranges, or countries, with a 403:

auth.ts
blocklist({
  ip: {
    values: ["203.0.113.7", "2001:db8::1"],
    ranges: ["198.51.100.0/24", "2001:db8:bad::/48"],
    allow: ["198.51.100.10"], // always allowed, also an address or a range
    countries: ["KP"],
    // Only when your app runs behind Cloudflare, which sets this header.
    getCountry: ({ headers }) => headers.get("cf-ipcountry"),
  },
});
{ "code": "IP_ADDRESS_NOT_ALLOWED", "message": "Signing up or signing in from this network or location is not allowed" }
  • Where: scope picks "sign-up" (creating users), "sign-in" (creating sessions, including the automatic sign-in after sign-up), or both, the default. /sign-up/* and /sign-in/* are checked before the handler runs, so a blocked client doesn't even learn whether a password was right. Users and sessions are checked again when they are created, which covers OAuth callbacks, magic links, and every other way in. Admin endpoints (/admin/*) aren't checked, and existing sessions are not revoked.
  • Which address: the one better-auth uses for rate limiting, from its advanced.ipAddress settings (ipAddressHeaders, trustedProxies, disableIpTracking). IPv6 addresses are compared in full, not collapsed to their /64 network as for rate limiting; use a range to block a network. Without an address, only country rules apply.
  • Countries: getCountry returns the two-letter country code of a request, usually from a header your host or proxy sets: cf-ipcountry on Cloudflare (which also sends T1 for Tor), x-vercel-ip-country on Vercel, or request.cf.country in a Cloudflare Worker. There is no built-in geo-IP database. If getCountry throws, the error is logged and the country counts as unknown, like a request without the header: the request isn't failed, and address rules still apply.

Only trust headers your proxy sets

Clients can send cf-ipcountry or x-forwarded-for themselves. Read a header only when a proxy in front of your app always sets it, and configure better-auth's trustedProxies so the forwarded address is the client's. IP and country rules keep out casual abuse; they are not a security boundary against someone with a VPN.

genericErrorMessage doesn't apply to ip: there is no form field to hide.

Rule types

A rule is a plain string (an exact rule) or an object with a type:

TypeBlocks the value when it...Example rule
exactequals the rule"admin"
domainis an email whose domain is the rule or a subdomain of it{ value: "mailinator.com", type: "domain" }
prefixstarts with the rule{ value: "support", type: "prefix" }
suffixends with the rule{ value: "-bot", type: "suffix" }
containscontains the rule{ value: "official", type: "contains" }
regexmatches the rule as a regular expression{ value: "^admin\\d+$", type: "regex" }
cidris an IP address inside the range{ value: "198.51.100.0/24", type: "cidr" }
countrycomes from the country (see getCountry){ value: "KP", type: "country" }

Rules can carry a reason, which is passed to onBlocked. domain rules only work for email. The ip target takes exact (an address), cidr, and country rules only, and no other target takes cidr or country. Invalid static rules throw when the plugin is created, so mistakes show up at startup.

Regular expressions

A slow pattern runs on every sign-up, so regex rules are restricted to patterns whose matching time stays bounded. Rejected are patterns that are invalid or longer than 200 characters, and patterns with:

  • a quantified group that contains a quantifier or an alternation, at any depth, such as (a+)+, ((a+))+, or (a|aa)+;
  • more than two unbounded quantifiers (*, +, {n,}, and {n} or {n,m} above 10 repetitions), such as .*.*.*x;
  • more than eight quantifiers in total;
  • backreferences such as \1 or \k<name>.

A regex rule only runs on values up to 256 characters. Longer values are blocked by it, because they can't be checked safely. Valid emails (at most 254 characters) and usernames with the username plugin's default limit (30) always fit. Only let trusted admins create regex rules.

Normalization

Values and rules are compared after normalization. Checked values are never stored normalized; rules created through the endpoints are (see Create a rule).

  1. Trim and lowercase (always).
  2. Unicode compatibility forms, so fullwidth ADMIN or the ligature fi become plain letters.
  3. Remove invisible characters, such as zero-width spaces, soft hyphens, bidi controls, and variation selectors, so admin with a zero-width space inside still matches admin.
  4. Remove accents, so ádmin and the Turkish ADMİN match admin. Marks that tell words apart in other scripts, such as Japanese dakuten or Hindi and Thai vowel signs, are kept.
  5. Fold common confusable characters, so a Cyrillic а, a Greek ο, or the Turkish dotless ı matches the Latin letter.
  6. For emails, drop trailing dots of the domain (mailinator.com. is the same host as mailinator.com), and ignore a +tag in the local part (stripPlusAddressing).
  7. For passwords, fold leetspeak (@ and 4 to a, 0 to o, 1, l, !, and | to i, 3 to e, $ and 5 to s, ...), except for regex rules.

IP addresses and ranges are compared in their canonical form instead, so 2001:0DB8::0001 and 2001:db8::1 are the same address, and ::ffff:192.0.2.1 is 192.0.2.1.

Steps 2 to 5 can be turned off with normalize: false. A regex runs against the normalized value, so write it in lowercase: a pattern with an uppercase letter (outside escapes such as \d or \p{L}) is rejected.

Predefined lists

@checodo/better-auth-blocklist/lists exports ready-made lists. They are opt-in, in a separate entry point, so they only load when you import them.

auth.ts
import { blocklist } from "@checodo/better-auth-blocklist";
import {
  disposableEmailDomains,
  reservedUsernames,
} from "@checodo/better-auth-blocklist/lists";

blocklist({
  email: { domains: disposableEmailDomains },
  username: { values: reservedUsernames },
  organization: { values: reservedUsernames },
});
ExportEntriesContent
disposableEmailDomains~32,000Domains of disposable (temporary) email providers
privacyRelayDomains13Domains of privacy relays (Firefox Relay, DuckDuckGo, SimpleLogin, ...)
reservedUsernames~500System, route, and role names such as admin, api, support

Each list is also its own entry point, to load only what you need:

import { disposableEmailDomains } from "@checodo/better-auth-blocklist/lists/disposable-email-domains";
import { privacyRelayDomains } from "@checodo/better-auth-blocklist/lists/privacy-relay-domains";
import { reservedUsernames } from "@checodo/better-auth-blocklist/lists/reserved-usernames";

Privacy relays

Relays such as Firefox Relay, DuckDuckGo Email Protection, SimpleLogin, addy.io, and Proton Pass give people a separate address per site and forward it to their real inbox. They aren't disposable, so disposableEmailDomains never contains them, and privacy-minded people can sign up with them.

One person can have any number of relay addresses, though. If you need one account per person (free trials, referral rewards), block them too:

auth.ts
import { blocklist } from "@checodo/better-auth-blocklist";
import { disposableEmailDomains, privacyRelayDomains } from "@checodo/better-auth-blocklist/lists";

blocklist({
  email: { domains: [...disposableEmailDomains, ...privacyRelayDomains] },
});

privacyRelayDomains is written by hand from each service's documentation. Fastmail Masked Email and iCloud Hide My Email use the provider's own domains (fastmail.com, icloud.com), so they can't be listed. Sign in with Apple's privaterelay.appleid.com isn't listed either: it gives one address per Apple ID and app, so it doesn't let anyone sign up twice, and blocking it would lock out everyone who hides their email when signing in with Apple. To count different forms of one address as one account, see Normalize.

How the domain list is built

disposableEmailDomains is generated from permissively licensed lists (CC0, MIT, BSD), each pinned to an exact commit: disposable-email-domains, burner-email-providers, mailchecker, fakefilter, disposable-email-domain-list, castle/disposable-email-domains, and jp-disposable-emails. Then:

  1. Invalid entries are dropped, and the rest is de-duplicated and sorted.
  2. Known legitimate mail services are removed: the allowlist and mail service list of disposable/disposable, major providers such as Gmail, Outlook, GMX, and Proton, and every privacy relay in privacyRelayDomains.
  3. Public suffixes such as net.ua or msk.ru are removed, checked against the Public Suffix List. Domain rules also match subdomains, so a suffix would block every domain registered under it.
  4. Every domain is checked in DNS (with public resolvers, not filtered local ones), and only domains that verifiably receive email are kept: they have a mail server (MX record) or an address that accepts mail. Domains that don't exist, refuse all mail, or can't be confirmed are removed, which is more than half of the merged list.

reservedUsernames comes from The Big Username Blacklist (MIT). The licenses ship in the package's THIRD_PARTY_NOTICES.md.

Good to know

  • The lists are snapshots taken when the package is released. Update the package to get newer ones.
  • Matching stays fast however long the list is (a few lookups per check). Loading the domain list takes some milliseconds and a few megabytes of memory, once, when the plugin is created.

No list is perfect. Combine lists with your own entries, and use allow for false positives:

blocklist({
  email: {
    domains: [...disposableEmailDomains, "spam.example"],
    allow: ["jane@flagged-but-fine.example"],
  },
});

Managing rules at runtime

Rules stored in the blocklistRule table apply on top of the static rules, right away, without a restart. Managing them requires a session whose user has one of adminRoles (the role field of better-auth's admin plugin) or is listed in adminUserIds. Requests without a session get a 401, other users a 403.

Create a rule

const { data, error } = await authClient.blocklist.createRule({
  target: "email", // "email" | "username" | "organization" | "team" | "password" | "ip"
  type: "domain", // defaults to "exact"
  value: "spam.example",
  reason: "Disposable provider", // optional
});

List rules

const { data } = await authClient.blocklist.listRules({
  query: { target: "email" }, // optional filter
});

Delete a rule

await authClient.blocklist.deleteRule({ id: "rule-id" });
EndpointClientServer
GET /blocklist/list-rulesauthClient.blocklist.listRulesauth.api.listBlocklistRules
POST /blocklist/create-ruleauthClient.blocklist.createRuleauth.api.createBlocklistRule
POST /blocklist/delete-ruleauthClient.blocklist.deleteRuleauth.api.deleteBlocklistRule

New rules are validated: duplicates, values longer than 255 characters, rule types the target doesn't take, unsafe regular expressions, invalid IP addresses, ranges, or country codes, country rules without getCountry, and targets with useDatabase: false are rejected. Values are stored the way they are matched (lowercase and normalized, domains without a leading @, IP addresses and ranges in canonical form, such as 198.51.100.0/24 for 198.51.100.77/24), so Spam.io and spam.io count as the same rule. Regular expressions are stored as written.

Database rules are cached for databaseCacheTtl (10 seconds by default). Changes through the endpoints apply right away on the server that made them; other servers pick them up when their cache expires.

Several servers

The cache is kept in each server process, not shared. With several instances or serverless functions, a new or deleted rule can take up to databaseCacheTtl to reach all of them. Rules from the plugin options are compiled at startup in every process, so they always agree. If a rule must apply everywhere at once, set databaseCacheTtl: 0: every check then reads the rules from the database.

With the audit log

With the audit log plugin, blocked sign-ups and changes, and the rules admins create and delete are recorded there too (see Events from other plugins).

Schema

Table: blocklistRule

Prop

Type

To rename the table or its columns, for example to match a snake_case database, use the schema option:

auth.ts
blocklist({
  schema: {
    blocklistRule: {
      modelName: "blocklist_rules",
      fields: { createdAt: "created_at" },
    },
  },
});

Error codes

Exported as BLOCKLIST_ERROR_CODES from both entry points, to compare with error.code:

import { BLOCKLIST_ERROR_CODES } from "@checodo/better-auth-blocklist/client";

if (error?.code === BLOCKLIST_ERROR_CODES.EMAIL_NOT_ALLOWED.code) {
  // show "Please use a permanent email address"
}
CodeStatusWhen
EMAIL_NOT_ALLOWED400A blocked email
USERNAME_NOT_ALLOWED400A blocked username
ORGANIZATION_NAME_NOT_ALLOWED400A blocked organization name or slug
TEAM_NAME_NOT_ALLOWED400A blocked team name
PASSWORD_NOT_ALLOWED400A password blocked by a rule
PASSWORD_CONTAINS_CONTEXT_WORD400A password with the email, username, or app name
IP_ADDRESS_NOT_ALLOWED403Sign-up or sign-in from a blocked IP or country
VALUE_NOT_ALLOWED400Any blocked value but an IP, with genericErrorMessage
YOU_ARE_NOT_ALLOWED_TO_MANAGE_BLOCKLIST_RULES403Rule endpoints, for users who aren't admins
RULE_ALREADY_EXISTS400Creating a duplicate rule
RULE_NOT_FOUND404Deleting a rule that doesn't exist
INVALID_REGEX_RULE400Creating an invalid or unsafe regex rule
REGEX_RULE_MUST_BE_LOWERCASE400Creating a regex rule with uppercase letters
DOMAIN_RULE_ONLY_FOR_EMAIL400Creating a domain rule outside email
RULE_TYPE_NOT_SUPPORTED_FOR_TARGET400Creating a rule of a type the target doesn't take
INVALID_IP_RULE400Creating an invalid IP, range, or country rule
COUNTRY_RULES_REQUIRE_GET_COUNTRY400Creating a country rule without getCountry
DATABASE_RULES_DISABLED_FOR_TARGET400Creating a rule for a target with useDatabase: false
RULE_VALUE_TOO_LONG400Creating a rule whose normalized value is too long

Options

Prop

Type

Target options

Prop

Type

Email options

In addition to the target options:

Prop

Type

Password options

The target options without allow, plus:

Prop

Type

IP options

In addition to the target options (values take exact addresses and cidr or country rules; allow takes addresses and ranges):

Prop

Type

On this page