diff --git a/docs/content/docs/plugins/username.mdx b/docs/content/docs/plugins/username.mdx index f1c2d71b..88ddfebd 100644 --- a/docs/content/docs/plugins/username.mdx +++ b/docs/content/docs/plugins/username.mdx @@ -96,6 +96,23 @@ const data = await authClient.updateUser({ }) ``` +### Check if username is available + +To check if a username is available, you can use the `isUsernameAvailable` function provided by the client. + +```ts title="auth-client.ts" +const response = await authClient.isUsernameAvailable({ + username: "new-username" +}); + +if(response.data?.available) { + console.log("Username is available"); +} else { + console.log("Username is not available"); +} +``` + + ## Schema The plugin requires 1 field to be added to the user table: diff --git a/packages/better-auth/src/plugins/username/index.ts b/packages/better-auth/src/plugins/username/index.ts index eac3dac3..b7891c55 100644 --- a/packages/better-auth/src/plugins/username/index.ts +++ b/packages/better-auth/src/plugins/username/index.ts @@ -224,6 +224,42 @@ export const username = (options?: UsernameOptions) => { }); }, ), + isUsernameAvailable: createAuthEndpoint( + "/is-username-available", + { + method: "POST", + body: z.object({ + username: z.string({ + description: "The username to check", + }), + }), + }, + async (ctx) => { + const username = ctx.body.username; + if (!username) { + throw new APIError("UNPROCESSABLE_ENTITY", { + message: ERROR_CODES.INVALID_USERNAME, + }); + } + const user = await ctx.context.adapter.findOne({ + model: "user", + where: [ + { + field: "username", + value: username.toLowerCase(), + }, + ], + }); + if (user) { + return ctx.json({ + available: false, + }); + } + return ctx.json({ + available: true, + }); + }, + ), }, schema: mergeSchema(schema, options?.schema), hooks: { diff --git a/packages/better-auth/src/plugins/username/username.test.ts b/packages/better-auth/src/plugins/username/username.test.ts index 127fc102..3b567181 100644 --- a/packages/better-auth/src/plugins/username/username.test.ts +++ b/packages/better-auth/src/plugins/username/username.test.ts @@ -111,4 +111,18 @@ describe("username", async (it) => { }); expect(res.error?.status).toBe(422); }); + + it("should check if username is unavailable", async () => { + const res = await client.isUsernameAvailable({ + username: "new_username_2.1", + }); + expect(res.data?.available).toEqual(false); + }); + + it("should check if username is available", async () => { + const res = await client.isUsernameAvailable({ + username: "new_username_2.2", + }); + expect(res.data?.available).toEqual(true); + }); });