Organization Best Practices
It covers setting up the plugin on both the server and client sides, creating organizations, controlling organization creation permissions, and managing acti...
Install
npx promptshop add organization-best-practicesDetails
What This Skill Does
This skill details how to implement organization management features using Better Auth's organization plugin. It covers setting up the plugin on both the server and client sides, creating organizations, controlling organization creation permissions, and managing active organizations. This is useful for developers building multi-tenant applications or platforms with organization-based access control.
When to Use
- Set up the organization plugin.
- Create new organizations.
- Control who can create organizations.
- Limit the number of organizations per user.
- Create organizations on behalf of users.
- Manage active organizations in the session.
Key Features
- Adds the
organization()plugin to the server config. - Adds the
organizationClient()plugin to the client config. - Provides code for creating organizations.
- Restricts organization creation based on user attributes.
- Allows admins to create orgs for other users.
- Stores active organizations in the session.
Manual Installation
Setup
- Add organization() plugin to server config
- Add organizationClient() plugin to client config
- Run npx @better-auth/cli migrate Verify: check that organization, member, invitation tables exist in your database
import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins";
export const auth = betterAuth({ plugins: [ organization({ allowUserToCreateOrganization: true, organizationLimit: 5, // Max orgs per user membershipLimit: 100, // Max members per org }), ], });
Client-Side Setup
import { createAuthClient } from "better-auth/client"; import { organizationClient } from "better-auth/client/plugins";
export const authClient = createAuthClient({ plugins: [organizationClient()], });
Creating Organizations
- The creator is automatically assigned the owner role.
const createOrg = async () => { const { data, error } = await authClient.organization.create({ name: "My Company", slug: "my-company", logo: "https://example.com/logo.png", metadata: { plan: "pro" }, }); };
Controlling Organization Creation
Restrict who can create organizations based on user attributes:
organization({ allowUserToCreateOrganization: async (user) => { return user.emailVerified === true; }, organizationLimit: async (user) => { // Premium users get more organizations return user.plan === "premium" ? 20 : 3; }, });
Creating Organizations on Behalf of Users
Administrators can create organizations for other users (server-side only):
await auth.api.createOrganization({ body: { name: "Client Organization", slug: "client-org", userId: "user-id-who-will-be-owner", // userId is required }, });
Note: The userId parameter cannot be used alongside session headers.
Active Organizations
- Stored in the session and scopes subsequent API calls.
- Set after user selects one.
const setActive = async (organizationId: string) => { const { data, error } = await authClient.organization.setActive({ organizationId, }); };
Many endpoints use the active organization when organizationId is not provided (list
Members
, listInvitations, inviteMember, etc.).
Use getFullOrganization() to retrieve the active org with all members, invitations, and teams. Members
Adding Members (Server-Side)
await auth.api.addMember({ body: { userId: "user-id", role: "member", organizationId: "org-id", }, });
For client-side member additions, use the invitation system instead.
Assigning Multiple Roles
await auth.api.addMember({ body: { userId: "user-id", role: ["admin", "moderator"], organizationId: "org-id", }, });
Removing Members
Use removeMember({ memberIdOrEmail }). The last owner cannot be removed — assign ownership to another member first.
Updating Member Roles
- Use updateMemberRole({ memberId, role }).
Membership Limits
organization({ membershipLimit: async (user, organization) => { if (organization.metadata?.plan === "enterprise") { return 1000; } return 50; }, });
Invitations
Setting Up Invitation Emails
import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; import { sendEmail } from "./email";
export const auth = betterAuth({ plugins: [ organization({ sendInvitationEmail: async (data) => { const { email, organization, inviter, invitation } = data;
await sendEmail({
to: email,
subject: Join ${organization.name},
html:
<p>${inviter.user.name} invited you to join ${organization.name}</p>
<a href="https://yourapp.com/accept-invite?id=${invitation.id}">
Accept Invitation
</a>
,
});
},
}),
], });
Sending Invitations
await authClient.organization.inviteMember({ email: "newuser@example.com", role: "member", });
Shareable Invitation URLs
const { data } = await authClient.organization.getInvitationURL({ email: "newuser@example.com", role: "member", callbackURL: "https://yourapp.com/dashboard", });
// Share data.url via any channel
This endpoint does not call sendInvitationEmail — handle delivery yourself.
Invitation Configuration
organization({ invitationExpiresIn: 60 60 24 * 7, // 7 days (default: 48 hours) invitationLimit: 100, // Max pending invitations per org cancelPendingInvitationsOnReInvite: true, // Cancel old invites when re-inviting });
Roles & Permissions
Default roles: owner (full access), admin (manage members/invitations/settings), member (basic access).
Checking Permissions
const { data } = await authClient.organization.hasPermission({ permission: "member:write", });
if (data?.hasPermission) { // User can manage members }
Use checkRolePermission({ role, permissions }) for client-side UI rendering (static only). For dynamic access control, use the hasPermission endpoint.
Teams
Enabling Teams
import { organization } from "better-auth/plugins";
export const auth = betterAuth({ plugins: [ organization({ teams: { enabled: true } }), ], });
Creating Teams
const { data } = await authClient.organization.createTeam({ name: "Engineering", });
Managing Team Members
Use addTeamMember({ teamId, userId }) (member must be in org first) and removeTeamMember({ teamId, userId }) (stays in org).
- Set active team with setActiveTeam({ teamId }).
Team Limits
organization({ teams: { maximumTeams: 20, // Max teams per org maximumMembersPerTeam: 50, // Max members per team allowRemovingAllTeams: false, // Prevent removing last team } });
Dynamic Access Control
Enabling Dynamic Access Control
import { organization } from "better-auth/plugins"; import { dynamicAccessControl } from "@better-auth/organization/addons";
export const auth = betterAuth({ plugins: [ organization({ dynamicAccessControl: { enabled: true } }), ], });
Creating Custom Roles
await authClient.organization.createRole({ role: "moderator", permission: { member: ["read"], invitation: ["read"], }, });
Use updateRole({ roleId, permission }) and deleteRole({ roleId }). Pre-defined roles (owner, admin, member) cannot be deleted.
- Roles assigned to members cannot be deleted until reassigned.
Lifecycle Hooks
Execute custom logic at various points in the organization lifecycle:
organization({ hooks: { organization: { beforeCreate: async ({ data, user }) => { // Validate or modify data before creation return { data: { ...data, metadata: { ...data.metadata, createdBy: user.id }, }, }; }, afterCreate: async ({ organization, member }) => { // Post-creation logic (e.g.,