DevOps & Cloud

How to Secure Supabase Applications: Preventing Data Leaks

A detailed guide to securing your Supabase database by properly configuring Row Level Security to prevent unauthorized access.

By · · 7 min read

Short answer

Data leaks in Supabase applications often stem from overly permissive Row Level Security (RLS) policies. To secure your app, ensure every table has explicit SELECT, INSERT, UPDATE, and DELETE policies, avoid generic public access, and audit your schema for misconfigurations regularly to prevent unauthorized database access.

Key takeaways

  • Row Level Security (RLS) is disabled by default on new tables; enabling it is the first line of defense.
  • Avoid using 'public' roles for CRUD operations in production applications.
  • Always define policies scoped to the authenticated user's UUID using auth.uid().
  • Regularly audit your Supabase dashboard for tables with 'allow all' policies.

Why RLS misconfigurations cause data leaks

Supabase functions by exposing your PostgreSQL database directly to the client via a REST or GraphQL API. Because your frontend application sends requests directly to the database, you cannot rely on a backend layer to filter sensitive information. Instead, Supabase relies on PostgreSQL Row Level Security (RLS) to act as the gatekeeper. When RLS is disabled, any user with your project API key can query, modify, or delete your entire database without restriction. The recent exposure of user data in platforms like Lovable highlights that even with RLS enabled, developers often write overly permissive policies that grant broad read or write access.

A common failure pattern involves creating policies that check for the existence of a row but fail to verify ownership. For example, if you create a policy that simply checks if a user is 'authenticated,' any logged-in user can access any row in the table, regardless of who created it. This completely invalidates the tenant isolation required for multi-tenant SaaS applications. When security is handled at the row level, a single missing user_id check effectively turns a private database into a public one for every user who holds a valid authentication token. Every time you define a policy, you must confirm that the criteria include a constraint that ties the record explicitly to the specific user account requesting the data.

Furthermore, developers often overlook the default state of new tables. While Supabase makes it easy to add new tables through the dashboard, it is the responsibility of the developer to toggle the 'Enable RLS' switch. If this step is missed during the initial schema design, the table is exposed immediately upon deployment. This oversight is particularly common when migrating existing database schemas from local environments where developers prioritized speed over strict access control.

How to audit your Supabase RLS policies

Auditing your database is the most effective way to identify vulnerabilities before they are exploited. You should start by manually reviewing the 'Authentication' -> 'Policies' section in your Supabase dashboard. This interface provides a visual summary of every table and the active policies associated with them. Look specifically for any table that displays policies using the 'public' role, as this allows unauthorized, anonymous access to that data.

In addition to the visual dashboard, you should perform automated checks. Run the following SQL query in your SQL editor to list all tables that currently have RLS disabled. These tables are currently exposed to anyone who has your public API key. This query queries the internal pg_tables system catalog, which tracks the security status of every object in your schema. By running this during your CI/CD pipeline, you can prevent insecure configurations from ever reaching production environments.

After identifying tables with disabled security, enable RLS for each one. Once enabled, ensure that you have at least one policy for every CRUD operation. Even if you want a table to be completely inaccessible to the client, having RLS enabled with no policies results in a 'deny all' state, which is much safer than an 'allow all' state. Regularly reviewing these outputs will help you catch tables that were added during development and never secured before the project was launched.

SELECT tablename
FROM pg_tables
WHERE rowsecurity = false
AND schemaname = 'public';

Secure RLS code patterns

The goal of a secure RLS policy is to restrict operations to the specific user who owns the record. You should always use the auth.uid() function to compare the current user's ID against a column in your table (usually user_id or created_by). This function retrieves the UID directly from the JWT (JSON Web Token) provided in the request header, meaning the database is trusting the authentication metadata supplied by the Supabase Auth system rather than relying on client-side input.

When designing your tables, you should consistently name your owner columns. Using a standard naming convention like user_id across your entire database makes it easier to write reusable RLS policies and reduces the mental overhead when auditing. If you are building a multi-tenant app, ensure your user_id column is indexed. This not only keeps your security checks performant but also ensures that every query is forced to filter by the owner's identity at the database level. Without an index, PostgreSQL may need to perform a sequential scan on the entire table to verify the policy, which can lead to significant latency as your user base grows.

Another aspect of secure coding involves the USING and WITH CHECK clauses. A USING expression defines which rows are visible to the user during a SELECT, UPDATE, or DELETE operation. A WITH CHECK expression defines whether a row is allowed to be inserted or updated to meet the criteria. If you omit the WITH CHECK clause, PostgreSQL uses the USING expression by default, but it is better practice to be explicit. Being explicit avoids ambiguity and ensures that your data integrity constraints are clear to any other developer looking at your schema.

-- Create a policy that allows users to only read their own rows
CREATE POLICY "Users can view their own data" ON profiles
FOR SELECT
USING (auth.uid() = id);

-- Create a policy that allows users to update their own rows
CREATE POLICY "Users can update their own data" ON profiles
FOR UPDATE
USING (auth.uid() = id);

Comparison: Default vs. Secure RLS policies

The table below compares common configuration mistakes versus secure implementations for production environments. Understanding these categories is essential for maintaining a high security posture. A 'Permissive' policy is essentially the same as having no security at all, as it returns 'true' for every row check. The 'Authenticated Users' policy is slightly better but still vulnerable in a multi-tenant environment, as it grants access to any logged-in user rather than the specific owner of the record. The 'Owner-Only' policy is the gold standard for most application data.

Policy TypeRisk LevelImplementation
Permissive (Allow All)CriticalUSING (true)
Authenticated UsersHighUSING (auth.role() = 'authenticated')
Owner-OnlyLowUSING (auth.uid() = user_id)
Service Role BypassMediumUse only for backend tasks

Gotchas: AI-generated SQL and insecure defaults

AI coding assistants often suggest SQL that works for local prototypes but is dangerous in production. They may generate code using 'authenticated' roles rather than scoped user IDs to make the code easier to integrate during the initial build phase. While this results in less friction while building your UI, it creates a massive security hole that could lead to data exposure. Always review generated migrations manually. Never copy-paste RLS policies without checking if they restrict access based on the user's specific UUID.

Another point of failure is when you use tools that auto-generate your schema. Some ORMs or database management tools might reset policies to default or disable them entirely when they push changes to your database. You should verify the state of your RLS policies after every migration, especially if your tooling is not explicitly Supabase-aware. If you notice that your policies are being overwritten, you should switch to using manual SQL migration files that explicitly define the CREATE POLICY statements in the correct order, ensuring that they are executed as part of your deployment process.

Finally, ensure that you are not accidentally exposing your 'service_role' key in client-side code. This key bypasses all RLS policies. It is intended only for backend processes where you have full control over the environment. If this key is found in your frontend code, your entire database security strategy is effectively nullified, as a malicious actor could use this key to perform administrative database operations, bypass RLS, and access all data in your system.

Frequently asked questions

Is RLS enough to secure a Supabase app?

RLS is the primary layer, but you should also implement proper database connection management, use environment variables for sensitive keys, and monitor your database logs for suspicious access patterns. Treat RLS as the foundation of your security, but supplement it with application-level checks and secure key management.

Does enabling RLS slow down my database?

RLS policies are executed by the PostgreSQL engine. When policies are properly indexed and structured, the performance impact is negligible for most applications. Proper indexing of the columns used in your USING clauses is essential to keep queries fast as your table sizes increase.

Can I bypass RLS for administrative tasks?

Yes, you can use the Supabase service role key, which bypasses RLS entirely. Only use this key in secure server-side environments and never expose it in client-side code or browser-based applications. Always manage this key through environment variables on your server.

Sources & further reading

About the author

Tushar Gautam is a full-stack & ai product engineer in India. He builds AI SaaS products such as an AI video ad generator, a RAG chatbot platform and a Razorpay-powered report service, mostly with Next.js, Flask and the Gemini API. See the projects, GitHub or LinkedIn.

This article was drafted with the help of AI (Google Gemini) from trending topics and published by Tushar Gautam. Spotted an error? Let me know.