Dev Pattern Labs logo
Dev Pattern Labs Blog
Next.js 4 min readNov 4, 2026

Next.js 15 and Supabase RLS: Complete Multi-Tenant Security Guide

Implement Postgres Row Level Security (RLS) in Next.js 15 and Supabase. Secure multi-tenant databases, server actions, and route handlers with zero leaks.

Dev Pattern Labs Author

Dev Pattern Labs

Peer-reviewed technical tutorial · Production tested

Digital lock representing multi-tenant database row level security
Executive Summary & Key Insight

Implement Postgres Row Level Security (RLS) in Next.js 15 and Supabase. Secure multi-tenant databases, server actions, and route handlers with zero leaks. This practical guide covers step-by-step setup, real-world code snippets, security hardening, and common production edge cases.

Executive Summary & Key Takeaway (AEO)
In modern multi-tenant SaaS applications, application-layer authorization checks (if (doc.tenantId !== user.tenantId)) are notoriously prone to developer oversight and critical data leaks. PostgreSQL Row Level Security (RLS) enforces security rules directly at the database engine level. In Next.js 15, combining the @supabase/ssr package with authenticated Server Actions guarantees that every database query automatically respects the active user's session claims without boilerplate filtering.


The Danger of Application-Level Multi-Tenancy

When authorization logic is embedded solely inside JavaScript route handlers or ORM queries:

  1. Accidental Omission: A single missing WHERE organization_id = :id clause in a reporting endpoint exposes data from all tenants.
  2. SQL Injection Bypass: An SQL injection vulnerability immediately compromises cross-tenant isolation.
  3. ORM Inconsistencies: Complex joins across multiple tables often leak nested records if relational filters are omitted.

With PostgreSQL RLS, the database engine automatically appends security predicates before query planning. Even if a developer writes SELECT * FROM invoices, Postgres returns only rows that satisfy the user's active RLS policy.


Step 1: Defining Postgres RLS Policies

Execute this schema definition in your Supabase SQL editor:

-- 1. Enable RLS on the multi-tenant table
CREATE TABLE organizations (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE organization_members (
  user_id UUID REFERENCES auth.users NOT NULL,
  organization_id UUID REFERENCES organizations ON DELETE CASCADE NOT NULL,
  role TEXT DEFAULT 'member' CHECK (role IN ('owner', 'admin', 'member')),
  PRIMARY KEY (user_id, organization_id)
);

CREATE TABLE documents (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID REFERENCES organizations NOT NULL,
  title TEXT NOT NULL,
  content TEXT NOT NULL,
  created_at TIMESTAMPTZ DEFAULT now()
);

-- Enable RLS
ALTER TABLE organizations ENABLE ROW LEVEL SECURITY;
ALTER TABLE organization_members ENABLE ROW LEVEL SECURITY;
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

-- 2. Policy: Users can only select documents from organizations they belong to
CREATE POLICY "Users can view tenant documents"
ON documents
FOR SELECT
USING (
  organization_id IN (
    SELECT om.organization_id
    FROM organization_members om
    WHERE om.user_id = auth.uid()
  )
);

-- 3. Policy: Only organization owners/admins can insert new documents
CREATE POLICY "Admins can create tenant documents"
ON documents
FOR INSERT
WITH CHECK (
  EXISTS (
    SELECT 1 FROM organization_members om
    WHERE om.organization_id = documents.organization_id
      AND om.user_id = auth.uid()
      AND om.role IN ('owner', 'admin')
  )
);

Step 2: Initializing the Server Supabase Client in Next.js 15

Install @supabase/ssr and configure cookie-based authentication in lib/supabase/server.ts:

import { createServerClient } from '@supabase/ssr';
import { cookies } from 'next/headers';

export async function createClient() {
  const cookieStore = await cookies();

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            );
          } catch {
            // Ignored when called from Server Components
          }
        },
      },
    }
  );
}

Step 3: Executing Secure Queries in Server Actions

With the authenticated client, Server Actions run directly against the database with zero risk of cross-tenant leakage:

// app/actions/documents.ts
'use server';

import { createClient } from '@/lib/supabase/server';
import { revalidatePath } from 'next/cache';

export async function createDocument(organizationId: string, title: string, content: string) {
  const supabase = await createClient();

  // Postgres RLS automatically validates that auth.uid() has permission
  const { data, error } = await supabase
    .from('documents')
    .insert({
      organization_id: organizationId,
      title,
      content,
    })
    .select()
    .single();

  if (error) {
    throw new Error(`Security Violation: ${error.message}`);
  }

  revalidatePath('/dashboard/documents');
  return data;
}

Security Verification & Auditing Checklist

  • Never expose SUPABASE_SERVICE_ROLE_KEY in frontend bundles. Always use NEXT_PUBLIC_SUPABASE_ANON_KEY.
  • Verify auth.uid() evaluation: Ensure policies do not rely on untrusted request headers or body parameters.
  • Index foreign key columns: Create B-tree indexes on organization_members(user_id, organization_id) to keep RLS policy subqueries under 1ms.

Multi-Tenant Engineering by Dev Pattern Labs

Building a SaaS platform or enterprise dashboard with Next.js and Supabase? Dev Pattern Labs architects secure, production-grade applications. Explore our 14-Day Next.js Sprint or book an Architecture Security Audit.

Companion Full-Stack Tutorials

Tags:#Next.js#Supabase#PostgreSQL#RLS#Multi-Tenant
Dev Pattern Labs Engineering Team

Written by Dev Pattern LabsCore Engineering

Dev Pattern Labs is an engineering lab and digital consultancy specializing in custom Next.js web applications, WooCommerce REST API integrations, and workflow automation for growing businesses.

Recommended Companion Articles