{"record":{"id":"31036a16adeb5192","repo":"payloadcms/payload","slug":"unauthorized-you-must-be-logged-in-to-make-this-r-31036a","errorCode":null,"errorMessage":"Unauthorized, you must be logged in to make this request.","messagePattern":"Unauthorized, you must be logged in to make this request\\.","errorType":"exception","errorClass":"UnauthorizedError","httpStatus":401,"severity":"error","filePath":"packages/payload/src/utilities/canAccessAdmin.ts","lineNumber":24,"sourceCode":" * Protects admin-only routes, server functions, etc.\n * The requesting user must either:\n * a. pass the `access.admin` function on the `users` collection, if defined\n * b. match the `config.admin.user` property on the Payload config\n * c. if no user is present, and there are no users in the system, allow access (for first user creation)\n * @throws {Error} Throws an `Unauthorized` error if access is denied that can be explicitly caught\n */\nexport const canAccessAdmin = async ({ req }: { req: PayloadRequest }) => {\n  const incomingUserSlug = req.user?.collection\n  const adminUserSlug = req.payload.config.admin.user\n\n  if (incomingUserSlug) {\n    const adminAccessFn = req.payload.collections[incomingUserSlug]?.config.access?.admin\n\n    if (adminAccessFn) {\n      const canAccess = await adminAccessFn({ slug: incomingUserSlug, req })\n\n      if (!canAccess) {\n        throw new UnauthorizedError()\n      }\n      // Match the user collection to the global admin config\n    } else if (adminUserSlug !== incomingUserSlug) {\n      throw new UnauthorizedError()\n    }\n  } else {\n    const hasUsers = await req.payload.find({\n      collection: adminUserSlug,\n      depth: 0,\n      limit: 1,\n      pagination: false,\n    })\n\n    // If there are users, we should not allow access because of `/create-first-user`\n    if (hasUsers.docs.length) {\n      throw new UnauthorizedError()\n    }\n  }","sourceCodeStart":6,"sourceCodeEnd":42,"githubUrl":"https://github.com/payloadcms/payload/blob/00c58b35c0ed348ddc22daabf467b139727214fd/packages/payload/src/utilities/canAccessAdmin.ts#L6-L42","documentation":"Thrown by `canAccessAdmin` when the authenticated user collection defines an `access.admin` function and that function returns a falsy value. This is the primary, customizable admin-access gate -- it runs per-request on admin-protected routes and server functions.","triggerScenarios":"A logged-in user whose collection config includes `access: { admin: ({ req }) => boolean }` makes a request to an admin-gated route or server function, and the function evaluates to `false` (e.g. a role check fails).","commonSituations":"The `access.admin` function checks a role/permission field that is missing or wrong on the user document; a migration changed the user role field name; the function has a bug (e.g. `req.user.role === 'writer'` when the field is `req.user.roles` array); the user was created before the access logic was added and lacks the required attribute.","solutions":["Inspect the collection `access.admin` function logic and verify the user document satisfies its conditions.","Ensure the user document has the role/permission field the function checks.","Test the function in isolation with the actual `req.user` object.","Update the `access.admin` implementation if the role model changed."],"exampleFix":"// before\naccess: {\n  admin: ({ req }) => req.user.role === 'admin', // user has 'roles' array, not 'role'\n}\n\n// after\naccess: {\n  admin: ({ req }) => Array.isArray(req.user?.roles) && req.user.roles.includes('admin'),\n}","handlingStrategy":"validation","validationCode":"// Before making the admin request, verify the user passes the access.admin check\nconst adminAccessFn = collectionConfig.access?.admin\nif (adminAccessFn) {\n  const ok = await adminAccessFn({ slug: user.collection, req: syntheticReq })\n  if (!ok) throw new Error('User fails access.admin check')\n}","typeGuard":null,"tryCatchPattern":"try {\n  await adminAction()\n} catch (e) {\n  if (e instanceof UnauthorizedError) {\n    // inspect access.admin logic; ensure user has required role/permission\n  } else throw e\n}","preventionTips":["Define access.admin explicitly on every auth collection that needs admin gating.","Unit-test the access.admin function against representative user documents.","Ensure user documents have the role/permission fields the function checks.","Handle UnauthorizedError gracefully in the UI with a login redirect."],"tags":["authorization","admin","access-control"],"backgroundTag":null,"analyzedSha":"00c58b35c0ed348ddc22daabf467b139727214fd","analyzedAt":"2026-08-12T20:45:03.758Z","schemaVersion":2},"datasetVersion":"2026-08-12T23:17:12.415Z"}