How to Fix Row Level Security (RLS) Bypass in Next.js
Learn how to prevent and fix Row Level Security (RLS) Bypass vulnerabilities in Next.js applications. Step-by-step guide with code examples, security checklists, and best practices.
What Is Row Level Security (RLS) Bypass?
Row Level Security (RLS) Bypass is a vulnerability specific to applications using database-level access control policies, most commonly with PostgreSQL (used by Supabase). RLS policies define which rows a given user can read, insert, update, or delete. A bypass occurs when these policies are missing, misconfigured, or can be circumvented, allowing users to access data they should not see.
Common RLS bypass scenarios include: tables with RLS not enabled (all data is accessible by default in Supabase when accessed through the API); overly permissive policies (e.g., allowing all authenticated users to read all rows); policies that only check SELECT but not UPDATE or DELETE; using service_role keys in client-side code (bypasses all RLS); policies that reference `auth.uid()` but do not account for all access paths; missing policies on junction tables in many-to-many relationships; and policies that can be bypassed through PostgreSQL functions that run with `SECURITY DEFINER`.
In Supabase applications, RLS bypass is particularly critical because the database is directly accessible from the client through the Supabase JavaScript SDK. Unlike traditional server-client architectures where the server mediates all data access, Supabase's client SDK makes direct PostgREST calls. This means RLS is often the only access control mechanism between the user and the data.
Why It Matters
In applications using Supabase or similar database-direct architectures, RLS is the primary security boundary. If RLS is bypassed, attackers can read all data from any table (including other users' data, admin data, and sensitive information), modify or delete records belonging to other users, escalate privileges by modifying their own user record, and access data across tenant boundaries in multi-tenant SaaS applications. Because Supabase exposes the PostgREST API directly and the `anon` key is inherently public (embedded in client code), any table without proper RLS policies is completely exposed. This has been a leading source of data breaches in Supabase applications.
How to Fix It in Next.js
Enable RLS on every table that contains user data. Create explicit policies for each operation (SELECT, INSERT, UPDATE, DELETE) -- do not rely on a single permissive policy. Use `auth.uid()` in policies to filter rows by the authenticated user. Test policies by querying as different users. Never use the `service_role` key in client-side code. Create separate policies for different user roles (admin, user, public). Apply policies to junction tables and related tables, not just primary tables. Use `SECURITY INVOKER` (default) for functions unless you specifically need elevated privileges. Audit all tables regularly with `SELECT tablename, rowsecurity FROM pg_tables WHERE schemaname = 'public'`. Test RLS policies as part of your CI/CD pipeline. Consider using Supabase's built-in RLS testing tools.
Next.js-Specific Advice
- Use Server Components for data fetching to keep secrets off the client bundle. Only `NEXT_PUBLIC_` prefixed env vars are exposed to the browser.
- Enable strict Content Security Policy headers in `next.config.js` using the `headers()` function. Block inline scripts and restrict allowed origins.
- Validate all Server Action inputs with Zod or a similar schema validator. Server Actions are public HTTP endpoints -- treat them like API routes.
- Use `next/headers` to access cookies securely in Server Components. Never parse cookies manually from request headers.
Code Examples
// DANGEROUS -- service_role bypasses all RLS policies
// This key must NEVER be in client-side code or NEXT_PUBLIC_ vars
import { createClient } from "@supabase/supabase-js";
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY! // Bypasses RLS!
);
// Also dangerous: table without RLS enabled
// Any authenticated user can read ALL rows// Use the anon key for client-side access
import { createServerClient } from "@supabase/ssr";
// Server component: create client with user's session
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ cookies }
);
// Ensure RLS is enabled and policies are defined:
// ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
// CREATE POLICY "Users can only see own projects"
// ON projects FOR SELECT
// USING (auth.uid() = user_id);
const { data } = await supabase
.from("projects")
.select("*"); // RLS automatically filters to user's rowsNext.js Security Checklist for Row Level Security (RLS) Bypass
Next.js Security Best Practices
Use Server Components for data fetching to keep secrets off the client bundle. Only `NEXT_PUBLIC_` prefixed env vars are exposed to the browser.
Enable strict Content Security Policy headers in `next.config.js` using the `headers()` function. Block inline scripts and restrict allowed origins.
Validate all Server Action inputs with Zod or a similar schema validator. Server Actions are public HTTP endpoints -- treat them like API routes.
Use `next/headers` to access cookies securely in Server Components. Never parse cookies manually from request headers.
Configure `images.remotePatterns` in `next.config.js` to allowlist trusted image domains and prevent SSRF through the image optimization API.
Implement middleware-based authentication checks for protected routes using `NextResponse.redirect()` rather than client-side guards alone.
Use the built-in CSRF protection in Server Actions. For custom API routes, implement CSRF tokens manually or use the Origin header check.
Set `poweredByHeader: false` in `next.config.js` to remove the `X-Powered-By: Next.js` header that helps attackers fingerprint your stack.
Scan Your Next.js App with SafeVibe
Stop guessing if your Next.js app is vulnerable to Row Level Security (RLS) Bypass. Run an automated penetration test in minutes and get actionable results.
Start Free Scan