organization-best-practices
Skill923 starsChanged 5 months agoMITView on GitHub
Configure multi-tenant organizations, manage members and invitations, define custom roles and permissions, set up teams, and implement RBAC using Better Auth's organization plugin. Use when users need org setup, team management, member roles, access control, or the Better Auth organization plugin.
We split this skill into the rules it gives an agent
11 rules. 3 are common, 0 are distinctive, and 8 are very specific to this project.
3
Common
Most of the 6 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 8
Add organization() plugin to server config
- Very specific: line 9
Add organizationClient() plugin to client config
- Common: line 11
Verify: check that organization, member, invitation tables exist in your database
- Very specific: line 100
Use getFullOrganization() to retrieve the active org with all members, invitations, and teams.
- Very specific: line 132
Use removeMember({ memberIdOrEmail }).
- Very specific: line 217
Default roles: owner (full access), admin (manage members/invitations/settings), member (basic access).
- Very specific: line 231
Use checkRolePermission({ role, permissions }) for client-side UI rendering (static only).
- Very specific: line 261
Use addTeamMember({ teamId, userId }) (member must be in org first) and removeTeamMember({ teamId, userId }) (stays in org).
- Very specific: line 308
Use updateRole({ roleId, permission }) and deleteRole({ roleId }).
- Common: line 393
Always ensure ownership transfer before removing the current owner:
- Common: line 434
Only the invited email address can accept an invitation
“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
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 { organization } from "better-auth/plugins";
import { betterAuth } from "better-auth";
export const auth = betterAuth({
plugins: [
organization({
allowUserToCreateOrganization: true,
organizationLimit: 5, // Max orgs per user
membershipLimit: 100, // Max members per org
}),
],
});Client-Side Setup
import { organizationClient } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/client";
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 (listMembers, 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 { organization } from "better-auth/plugins";
import { betterAuth } from "better-auth";
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 channelThis 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 { dynamicAccessControl } from "@better-auth/organization/addons";
import { organization } from "better-auth/plugins";
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., send welcome email, create default resources)
await createDefaultResources(organization.id);
},
beforeDelete: async ({ organization }) => {
// Cleanup before deletion
await archiveOrganizationData(organization.id);
},
},
member: {
afterCreate: async ({ member, organization }) => {
await notifyAdmins(organization.id, `New member joined`);
},
},
invitation: {
afterCreate: async ({ invitation, organization, inviter }) => {
await logInvitation(invitation);
},
},
},
});Schema Customization
Customize table names, field names, and add additional fields:
organization({
schema: {
organization: {
modelName: "workspace", // Rename table
fields: {
name: "workspaceName", // Rename fields
},
additionalFields: {
billingId: {
type: "string",
required: false,
},
},
},
member: {
additionalFields: {
department: {
type: "string",
required: false,
},
title: {
type: "string",
required: false,
},
},
},
},
});Security Considerations
Owner Protection
- The last owner cannot be removed from an organization
- The last owner cannot leave the organization
- The owner role cannot be removed from the last owner
Always ensure ownership transfer before removing the current owner:
// Transfer ownership first
await authClient.organization.updateMemberRole({
memberId: "new-owner-member-id",
role: "owner",
});
// Then the previous owner can be demoted or removedOrganization Deletion
Deleting an organization removes all associated data (members, invitations, teams). Prevent accidental deletion:
organization({
disableOrganizationDeletion: true, // Disable via config
});Or implement soft delete via hooks:
organization({
hooks: {
organization: {
beforeDelete: async ({ organization }) => {
// Archive instead of delete
await archiveOrganization(organization.id);
throw new Error("Organization archived, not deleted");
},
},
},
});Invitation Security
- Invitations expire after 48 hours by default
- Only the invited email address can accept an invitation
- Pending invitations can be cancelled by organization admins
Complete Configuration Example
import { organization } from "better-auth/plugins";
import { betterAuth } from "better-auth";
import { sendEmail } from "./email";
export const auth = betterAuth({
plugins: [
organization({
// Organization limits
allowUserToCreateOrganization: true,
organizationLimit: 10,
membershipLimit: 100,
creatorRole: "owner",
// Slugs
defaultOrganizationIdField: "slug",
// Invitations
invitationExpiresIn: 60 * 60 * 24 * 7, // 7 days
invitationLimit: 50,
sendInvitationEmail: async (data) => {
await sendEmail({
to: data.email,
subject: `Join ${data.organization.name}`,
html: `<a href="https://app.com/invite/${data.invitation.id}">Accept</a>`,
});
},
// Hooks
hooks: {
organization: {
afterCreate: async ({ organization }) => {
console.log(`Organization ${organization.name} created`);
},
},
},
}),
],
});Other versions6 projects use a version of this.
Word for word · 0
None found.
Edited · 6
- lukevella/rallly★ 5.3k58% same
- ever-works/ever-works★ 18597% same
- ssdeanx/AgentStack★ 4497% same
- krivoox/agent-stack-template★ 3195% same
- sprioleau/flock★ 195% same
- davidanthonyn/claude-skills★ 097% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository30 other files it gives its agents.
- .agents/skills/composition-patterns/AGENTS.mdAGENTS.md
- .agents/skills/react-best-practices/AGENTS.mdAGENTS.md
- .agents/skills/react-hook-form/AGENTS.mdAGENTS.md
- .agents/skills/zod/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/nextjs-cursor-rule.mdcCursor rule
- accessibilitySkill
- bash-defensive-patternsSkill
- better-auth-best-practicesSkill
- vercel-composition-patternsSkill
- drizzle-ormSkill
- email-and-password-best-practicesSkill
- frontend-designSkill
- neon-postgresSkill
- next-best-practicesSkill
- next-cache-componentsSkill
- next-upgradeSkill
- nodejs-backend-patternsSkill
- nodejs-best-practicesSkill
- vercel-react-best-practicesSkill
- react-hook-formSkill
- seoSkill
- shadcnSkill
- tailwind-css-patternsSkill
- tailwind-v4-shadcnSkill
- turborepoSkill
- two-factor-authentication-best-practicesSkill
- typescript-advanced-typesSkill
- ai-sdkSkill
- zodSkill
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
Reviews can't be read right now.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

