[GH-ISSUE #3779] feat(organization): Add support for sorting by nested user fields in listMembers API #18353

Closed
opened 2026-04-15 16:47:51 -05:00 by GiteaMirror · 2 comments
Owner

Originally created by @jensenAcolad on GitHub (Aug 4, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/3779

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Steps to Reproduce

  1. Setup Better Auth with organization plugin

    // auth.ts
    import { betterAuth } from "better-auth"
    import { organization } from "better-auth/plugins"
    
    export const auth = betterAuth({
      plugins: [organization()]
    })
    
  2. Create organization and add members

    const { data: org } = await authClient.organization.create({
      name: "Test Org",
      slug: "test-org"
    })
    
    // Add some members with different names
    
  3. Attempt to sort by user fields

    const { data, error } = await authClient.organization.listMembers({
      fetchOptions: {
        query: {
          organizationId: org.id,
          limit: 20,
          offset: 0,
          sortBy: "name", // ❌ This fails
          sortDirection: "asc"
        }
      }
    })
    
  4. Observe error

    Error: Field name not found in model member
    

Expected vs Actual

  • Expected: Members sorted by user name
  • Actual: Error thrown for nested field sorting

Working Alternatives

These work (member fields):

sortBy: "role"        // ✅ Works
sortBy: "createdAt"   // ✅ Works

These fail (user fields):

sortBy: "name"   // ❌ Fails
sortBy: "email"  // ❌ Fails

Current vs. Expected behavior

The listMembers API in the organization plugin currently doesn't support sorting by nested user fields (like name, email) when the response includes joined user data. This is a common use case for member management interfaces where users need to sort by user information.

Current Behavior

When calling listMembers with sorting by user fields:

await betterAuthClient.organization.listMembers({
  fetchOptions: {
    query: {
      organizationId: "org-id",
      limit: 20,
      offset: 0,
      sortBy: "user.name", // ❌ This fails
      sortDirection: "asc"
    }
  }
});

The API returns an error: Error: Field name not found in model member

Expected Behavior

The API should support sorting by nested user fields using dot notation (e.g., user.name, user.email) or provide an alternative syntax for sorting by joined table fields.

Technical Analysis

Looking at the current implementation in adapter.ts line 108, the listMembers function:

  1. Fetches members with sorting applied to the member table only
  2. Separately fetches user data and joins it in memory
  3. The sorting is applied before the join, so user fields aren't available for sorting

API Response Structure

The current response structure includes nested user data:

{
  "members": [
    {
      "id": "member-id",
      "userId": "user-id", 
      "organizationId": "org-id",
      "role": "owner",
      "createdAt": "2025-01-15T10:30:00Z",
      "user": {
        "id": "user-id",
        "name": "John Doe",
        "email": "john@example.com",
        "image": "avatar-url"
      }
    }
  ],
  "total": 50
}

What version of Better Auth are you using?

1.3.4

Provide environment information

Any Browser.

Which area(s) are affected? (Select all that apply)

Client

Auth config (if applicable)

import { magicLinkClient, organizationClient } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";

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

Additional context

No response

Originally created by @jensenAcolad on GitHub (Aug 4, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/3779 ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce ## Steps to Reproduce 1. **Setup Better Auth with organization plugin** ```typescript // auth.ts import { betterAuth } from "better-auth" import { organization } from "better-auth/plugins" export const auth = betterAuth({ plugins: [organization()] }) ``` 2. **Create organization and add members** ```typescript const { data: org } = await authClient.organization.create({ name: "Test Org", slug: "test-org" }) // Add some members with different names ``` 3. **Attempt to sort by user fields** ```typescript const { data, error } = await authClient.organization.listMembers({ fetchOptions: { query: { organizationId: org.id, limit: 20, offset: 0, sortBy: "name", // ❌ This fails sortDirection: "asc" } } }) ``` 4. **Observe error** ``` Error: Field name not found in model member ``` ## Expected vs Actual - **Expected**: Members sorted by user name - **Actual**: Error thrown for nested field sorting ## Working Alternatives These work (member fields): ```typescript sortBy: "role" // ✅ Works sortBy: "createdAt" // ✅ Works ``` These fail (user fields): ```typescript sortBy: "name" // ❌ Fails sortBy: "email" // ❌ Fails ``` ### Current vs. Expected behavior The `listMembers` API in the organization plugin currently doesn't support sorting by nested user fields (like `name`, `email`) when the response includes joined user data. This is a common use case for member management interfaces where users need to sort by user information. ### Current Behavior When calling `listMembers` with sorting by user fields: ```typescript await betterAuthClient.organization.listMembers({ fetchOptions: { query: { organizationId: "org-id", limit: 20, offset: 0, sortBy: "user.name", // ❌ This fails sortDirection: "asc" } } }); ``` The API returns an error: `Error: Field name not found in model member` ### Expected Behavior The API should support sorting by nested user fields using dot notation (e.g., `user.name`, `user.email`) or provide an alternative syntax for sorting by joined table fields. ### Technical Analysis Looking at the current implementation in [`adapter.ts` line 108](https://github.com/better-auth/better-auth/blob/987be984b4d840a409ca1e0d6098ee0f3303bcb6/packages/better-auth/src/plugins/organization/adapter.ts#L108), the `listMembers` function: 1. Fetches members with sorting applied to the member table only 2. Separately fetches user data and joins it in memory 3. The sorting is applied before the join, so user fields aren't available for sorting ### API Response Structure The current response structure includes nested user data: ```json { "members": [ { "id": "member-id", "userId": "user-id", "organizationId": "org-id", "role": "owner", "createdAt": "2025-01-15T10:30:00Z", "user": { "id": "user-id", "name": "John Doe", "email": "john@example.com", "image": "avatar-url" } } ], "total": 50 } ``` ### What version of Better Auth are you using? 1.3.4 ### Provide environment information ```bash Any Browser. ``` ### Which area(s) are affected? (Select all that apply) Client ### Auth config (if applicable) ```typescript import { magicLinkClient, organizationClient } from "better-auth/client/plugins"; import { createAuthClient } from "better-auth/react"; export const authClient = createAuthClient({ plugins: [magicLinkClient(), organizationClient()], }); ``` ### Additional context _No response_
GiteaMirror added the lockedenhancement labels 2026-04-15 16:47:51 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Aug 4, 2025):

Hi @jensenAcolad! I'm Dosu and I’m helping the better-auth team.

Sorting by nested user fields (like user.name or user.email) in the listMembers API isn't currently supported. The implementation applies sorting only to direct member fields before joining user data, which is why you see the "Field name not found in model member" error when trying to sort by user fields. This limitation is present in both the code and recent pull requests that added sorting and pagination—sorting by joined user fields would require a deeper change, such as supporting database joins with ORDER BY on user fields or in-memory sorting after joining user data. For now, the only workaround is to fetch the data and sort by user fields on the client side. There are no open issues or PRs tracking this specific feature yet, but a related feature request exists for multi-field sorting in listUsers, showing interest in more advanced sorting options from the community.
See implementation details
Recent PRs: #3581, #3623, #3624

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

<!-- gh-comment-id:3150814619 --> @dosubot[bot] commented on GitHub (Aug 4, 2025): <!-- Greeting --> Hi @jensenAcolad! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> Sorting by nested user fields (like `user.name` or `user.email`) in the `listMembers` API isn't currently supported. The implementation applies sorting only to direct member fields before joining user data, which is why you see the "Field name not found in model member" error when trying to sort by user fields. This limitation is present in both the code and recent pull requests that added sorting and pagination—sorting by joined user fields would require a deeper change, such as supporting database joins with `ORDER BY` on user fields or in-memory sorting after joining user data. For now, the only workaround is to fetch the data and sort by user fields on the client side. There are no open issues or PRs tracking this specific feature yet, but a related feature request exists for multi-field sorting in `listUsers`, showing interest in more advanced sorting options from the community. [See implementation details](https://github.com/better-auth/better-auth/blob/987be984b4d840a409ca1e0d6098ee0f3303bcb6/packages/better-auth/src/plugins/organization/adapter.ts) [Recent PRs: #3581, #3623, #3624](https://github.com/better-auth/better-auth/pull/3581) <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/72ebac5d-8f3b-4798-9e5a-943ca91a5b49?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/72ebac5d-8f3b-4798-9e5a-943ca91a5b49?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/72ebac5d-8f3b-4798-9e5a-943ca91a5b49?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/72ebac5d-8f3b-4798-9e5a-943ca91a5b49?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/72ebac5d-8f3b-4798-9e5a-943ca91a5b49?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/72ebac5d-8f3b-4798-9e5a-943ca91a5b49?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/72ebac5d-8f3b-4798-9e5a-943ca91a5b49?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/3779)
Author
Owner

@frectonz commented on GitHub (Aug 14, 2025):

Sorry, the current internal ORM used in Better Auth doesn’t support joins and sorting rows across joins. This will be one of the issues we address after adding support for joins.

In the meantime, you can achieve this by implementing your own list members endpoint that utilizes the ORM you’re using in your application, which is likely to support joins. Let me know if you need help with that.

<!-- gh-comment-id:3189682041 --> @frectonz commented on GitHub (Aug 14, 2025): Sorry, the current internal ORM used in Better Auth doesn’t support joins and sorting rows across joins. This will be one of the issues we address after adding support for joins. In the meantime, you can achieve this by implementing your own list members endpoint that utilizes the ORM you’re using in your application, which is likely to support joins. Let me know if you need help with that.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#18353