{"record":{"id":"a99de87e01a32a9f","repo":"payloadcms/payload","slug":"a-user-with-the-given-username-is-already-register","errorCode":null,"errorMessage":"A user with the given username is already registered.","messagePattern":"A user with the given username is already registered\\.","errorType":"validation","errorClass":"ValidationError","httpStatus":400,"severity":"error","filePath":"packages/payload/src/auth/strategies/local/register.ts","lineNumber":68,"sourceCode":"      whereConstraint.or?.push({\n        username: {\n          equals: doc.username,\n        },\n      })\n    }\n  }\n\n  const existingUser = await payload.find({\n    collection: collection.slug,\n    depth: 0,\n    limit: 1,\n    pagination: false,\n    req,\n    where: whereConstraint,\n  })\n\n  if (existingUser.docs.length > 0) {\n    throw new ValidationError({\n      collection: collection.slug,\n      errors: [\n        canLoginWithUsername\n          ? {\n              message: req.t('error:usernameAlreadyRegistered'),\n              path: 'username',\n            }\n          : { message: req.t('error:userEmailAlreadyRegistered'), path: 'email' },\n      ],\n    })\n  }\n\n  const { hash, salt } = await generatePasswordSaltHash({ collection, password, req })\n\n  const sanitizedDoc = { ...doc }\n  if (sanitizedDoc.password) {\n    delete sanitizedDoc.password\n  }","sourceCodeStart":50,"sourceCodeEnd":86,"githubUrl":"https://github.com/payloadcms/payload/blob/00c58b35c0ed348ddc22daabf467b139727214fd/packages/payload/src/auth/strategies/local/register.ts#L50-L86","documentation":"In `registerLocalStrategy`, after building a where-constraint by username (or username+email) it queries for existing users; on any match it throws a `ValidationError` carrying the localized `usernameAlreadyRegistered` message on the `username` path. Fires only when `canLoginWithUsername` is true (collection supports username login).","triggerScenarios":"Calling the register/create-first-user operation with a `username` (or email, when `canLoginWithEmail`) that already exists in a username-login-enabled auth collection.","commonSituations":"Duplicate signup attempt; re-running a seed/import script; only app-layer uniqueness enforcement (DB allows the race); username collision from a soft-deleted then restored user.","solutions":["Use a different username.","Add a pre-flight `payload.find({ where: { username: { equals } } })` check before register (note: still race-prone).","Enforce a unique index at the DB layer to eliminate the race."],"exampleFix":"// before\nawait payload.create({ collection: 'users', data: { username: 'taken', password, ... } })\n// after\nconst taken = await payload.find({ collection: 'users', limit: 1, pagination: false, where: { username: { equals: 'taken' } } })\nif (taken.docs.length) throw new Error('username taken')\nawait payload.create({ collection: 'users', data: { username: 'taken', password, ... } })","handlingStrategy":"try-catch","validationCode":"async function isUsernameAvailable(payload, slug, username) {\n  const res = await payload.find({ collection: slug, limit: 1, pagination: false, where: { username: { equals: username } } })\n  return res.docs.length === 0\n}","typeGuard":"function isValidationError(e): e is ValidationError {\n  return e?.name === 'ValidationError' && Array.isArray(e?.data?.errors)\n}","tryCatchPattern":"try {\n  await payload.create({ collection: 'users', data })\n} catch (e) {\n  if (isValidationError(e) && e.data.errors.some(x => x.path === 'username')) {\n    setFieldError('username', 'already taken')\n  } else throw e\n}","preventionTips":["Pre-check username availability (still race-prone without a DB constraint).","Enforce a unique index at the DB level.","Map the `ValidationError` to the username field on the form."],"tags":["auth","register","validation","username","duplicate"],"backgroundTag":null,"analyzedSha":"00c58b35c0ed348ddc22daabf467b139727214fd","analyzedAt":"2026-08-12T20:45:03.758Z","schemaVersion":2},"datasetVersion":"2026-08-12T23:17:12.415Z"}