Features
Multi-tenancy support

Multi-tenancy support

A tenant is an entity that can vary depending on the focus of your SaaS. If it is more B2B-oriented, a tenant could represent an organization or company. If it is B2C-focused, it might represent a project or even an individual. In any case, the term "tenant" adapts to how you wish to structure your application.

The key is to understand that a tenant is how we separate business logic within your SaaS, allowing users to manage their own resources in an isolated manner. At the same time, they can share those resources with a team or group of members without interfering with other tenants, thus ensuring security and autonomy in its usage.

 
  //src/lib/constants.ts
 
  export const constants = {
    multiTenant: true,
    tanantModelName: "Workspace", //Can be: Organization, Project, Workspace, etc
  }
 

Tenant Model

For standardization purposes, the model that stores the tenant in our database is called Organization. This Organization can have many members and has a membership plan.

Tenant = Organization
    model Organization {
        id                       Int                        @id @default(autoincrement())
        status                   OrganizationStatus         @default(ACTIVE)
        userMemberships          UserMembership[]
        settings                 OrganizationSetting[]
        subscription             Subscription?
        ...
    }

UserMembership Model

The user who registers on the platform automatically becomes the admin of the Tenant that is created by default along with their registration. However, they can invite other users to be part of this new Tenant. Each new user who is invited has a member role (unless otherwise specified). This way, the same user can have multiple memberships in different Tenants, being an admin in some and a member in others. Thus, we now have a new entity: UserMembership.

    model UserMembership {
        id             Int                     @id @default(autoincrement())
        userId         Int
        organizationId Int
        role           UserMembershipRole      @default(ADMIN)
        permissions    Permission[]
        isActive       Boolean                 @default(true)
        user           User                    @relation(fields: [userId], references: [id])
        organization   Organization            @relation(fields: [organizationId], references: [id], onDelete: Cascade)
        settings       UserMembershipSetting[]
 
        @@index([organizationId])
    }
 

Implementation in code

How to obtain the logged in user instance in each scenario:

Servers components, Server Actions, Apis

    const { organization, userMembership } = await getMembership();

Client components

    const { organization, userMembership } = await useMembership();