handler: createAuthMiddleware()

in packages/better-auth/src/plugins/username/index.ts [238:279]


					handler: createAuthMiddleware(async (ctx) => {
						const username = ctx.body.username;
						if (username !== undefined && typeof username === "string") {
							const minUsernameLength = options?.minUsernameLength || 3;
							const maxUsernameLength = options?.maxUsernameLength || 30;
							if (username.length < minUsernameLength) {
								throw new APIError("UNPROCESSABLE_ENTITY", {
									message: ERROR_CODES.USERNAME_TOO_SHORT,
								});
							}

							if (username.length > maxUsernameLength) {
								throw new APIError("UNPROCESSABLE_ENTITY", {
									message: ERROR_CODES.USERNAME_TOO_LONG,
								});
							}

							const validator =
								options?.usernameValidator || defaultUsernameValidator;

							const valid = await validator(username);
							if (!valid) {
								throw new APIError("UNPROCESSABLE_ENTITY", {
									message: ERROR_CODES.INVALID_USERNAME,
								});
							}
							const user = await ctx.context.adapter.findOne<User>({
								model: "user",
								where: [
									{
										field: "username",
										value: username.toLowerCase(),
									},
								],
							});
							if (user) {
								throw new APIError("UNPROCESSABLE_ENTITY", {
									message: ERROR_CODES.USERNAME_IS_ALREADY_TAKEN,
								});
							}
						}
					}),