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/ssrpackage 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:
- Accidental Omission: A single missing
WHERE organization_id = :idclause in a reporting endpoint exposes data from all tenants. - SQL Injection Bypass: An SQL injection vulnerability immediately compromises cross-tenant isolation.
- 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_KEYin frontend bundles. Always useNEXT_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
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

Dynamic Open Graph Image Generation with Next.js 15 and @vercel/og
Generate dynamic, high-converting Open Graph social preview cards in Next.js 15 using Satori and Edge Runtime. Boost social CTR and SEO indexation.

Next.js 15 Internationalization: App Router Multi-Language Guide
Configure multi-language localization in Next.js 15 App Router. Implement subpath routing, language middleware, translated metadata, and hreflang tags.

Next.js 15 Partial Prerendering: Complete Architecture Guide
Master Next.js 15 Partial Prerendering (PPR). Combine instant static shells with dynamic streaming Suspense holes for lightning-fast Core Web Vitals.
