Supabase

How to implement multi-tenancy with Supabase?

Dive into mastering multi-tenancy using Supabase. Uncover top practices, set up distinct schemas, handle user permission, and boost performance.

Developer profile skeleton
a developer thinking

Overview

Delving into multi-tenancy with Supabase requires grasping the architectural and security nuances to let various tenants share identical application resources without risking data integrity. Achieving this can be done using schema-based isolation, row-level security policies, and cleverness with API keys to partition tenant data. Appropriate configuration is vital for each tenant's data to be securely encapsulated and access controls rigidly applied. Strategically, it's necessary to tackle performance, maintainability, and scalability issues, all of which are essential hurdles in building robust multi-tenant systems.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to implement multi-tenancy with Supabase?

Step 1: Define Tenant Data Model

Alright, let's start by creating a table to store tenant-specific information. This table will have unique identifiers for each tenant and any other necessary metadata.

create table tenants (
    id uuid primary key default uuid_generate_v4(),
    name text not null,
    -- Add any other tenant-specific fields here
);

Step 2: Update User Table with Tenant ID

Next, we need to modify the existing user table to include a foreign key reference to the tenants' table. This way, we can link users to their respective tenants.

alter table users
add column tenant_id uuid references tenants(id);

Step 3: Set Up Row-Level Security (RLS)

Now, let's enable row-level security on the tables that will use multi-tenancy. This is crucial for isolating tenant data.

alter table users enable row level security;
alter table your_data_table enable row level security;

Step 4: Create RLS Policies for Isolation

Time to create RLS policies to ensure that tenants can only access their own data. This is where the magic happens!

For the users table:

create policy "Users can only access their own data" on users
    for select using (auth.uid() = id);

create policy "Users can insert into their own tenant" on users
    for insert with check (tenant_id = (select tenant_id from users where id = auth.uid()));

For the your_data_table:

create policy "Users only see their tenant's data" on your_data_table
    for select using (
        tenant_id = (select tenant_id from users where id = auth.uid())
    );

create policy "Users can insert their tenant's data" on your_data_table
    for insert with check (
        tenant_id = (select tenant_id from users where id = auth.uid())
    );

Step 5: Configure Supabase Auth for Tenancy Assignment

Ensure that the user creation process includes assigning the correct tenant ID. This can be done via a function or middleware in your backend logic.

Example: After user registration, update the user's tenant_id.

import { supabase } from './supabaseClient';

async function assignTenant(userId, tenantId) {
    const { data, error } = await supabase
        .from('users')
        .update({ tenant_id: tenantId })
        .eq('id', userId);
    
    if (error) {
        console.error('Error assigning tenant:', error);
    } else {
        console.log('Tenant assigned:', data);
    }
}

Step 6: Apply Multi-Tenant Logic in Your Application Code

When querying data, make sure tenant-specific logic is applied. Supabase's RLS policies usually handle this automatically. Just ensure your application's client passes the correct tenant context when performing operations.

Example: Fetch user-specific data.

const { data, error } = await supabase
    .from('your_data_table')
    .select('*')
    .eq('tenant_id', logged_in_user.tenant_id);
    
if (error) {
    console.error('Error fetching tenant data:', error);
} else {
    console.log('Tenant data:', data);
}

Step 7: Regularly Audit and Monitor

Regularly review the RLS policies and tenant data to ensure compliance and security. Regular cuts of database logs and audits will help maintain your multi-tenant setup's health.

-- Sample audit log query (if you have audit logs setup)
select * from audit_log where action = 'SELECT' and table_name = 'your_data_table';

Keep the system up-to-date with new tenants and maintain a log of all tenant-related actions.

Explore more Supabase tutorials

Complete Guide to Supabase: Tutorials, Tips, and Best Practices

Explore our Supabase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.