
On this page
Table of Contents
10 Common Supabase Errors and How to Fix Them
Supabase makes it easier to build applications with PostgreSQL, authentication, and ready-to-use APIs. But errors can become confusing when database permissions, authentication sessions, and application code interact.
An insert might work in the SQL Editor but fail in your Next.js application. A user might suddenly receive authentication errors. A table might exist in development but be missing after deployment.
The challenge is identifying which layer is actually failing.
Supabase applications involve several distinct components:
- PostgreSQL database
- Row Level Security (RLS)
- PostgREST database API
- Supabase Auth
- Database connection pooling
- Application and deployment configuration
Each component produces different errors.
This guide covers 10 common Supabase errors, what causes them, how to investigate them, and practical solutions for JavaScript and Next.js applications.
The examples focus on Supabase JavaScript v2, PostgreSQL, and the modern Next.js App Router.
Before running SQL: The examples use illustrative tables and policies. Review your existing schema, grants, and policies before applying changes. Use a disposable database for security-sensitive experiments.
1. New Row Violates Row-Level Security Policy
Example error:
new row violates row-level security policy
for table "todos"This commonly appears when inserting a record into an RLS-protected table.
Why it happens
PostgreSQL Row Level Security determines which rows a user is allowed to access or modify.
If RLS is enabled but an appropriate INSERT policy is missing, an ordinary authenticated request may not be allowed to create the row.
The same error can occur when an existing policy rejects the inserted values.
For example, suppose your todos table contains:
id
user_id
title
completedYour application may have a policy requiring user_id to match the authenticated user.
But your insert request might omit user_id or supply another user's ID.
How to fix it
First, inspect your existing policies and table grants.
For a table where users should only create their own todos, a suitable insert policy is:
create policy "Users insert own todos"
on public.todos
for insert
to authenticated
with check (
(select auth.uid()) = user_id
);This assumes RLS is already enabled, the table exists with a user_id UUID column, and the authenticated role has the necessary INSERT privilege.
Then make sure your application inserts the correct owner ID.
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
throw new Error("Authentication required");
}
const { error } = await supabase
.from("todos")
.insert({
title: "Review inventory",
user_id: user.id,
});
if (error) {
console.error(error.code, error.message);
}For stronger ownership enforcement, your schema can assign the owner ID server-side rather than trusting arbitrary browser input. RLS must still reject unauthorized values.
Common mistakes
- Creating a
SELECTpolicy but noINSERTpolicy. - Forgetting to enable RLS.
- Inserting another user's ID.
- Testing in a privileged SQL Editor session and assuming the browser has identical permissions.
- Adding an overly broad policy just to make the error disappear.
Important: A policy and a table grant are separate requirements. An operation can fail because the database role lacks a privilege even when the RLS policy appears correct.
2. Infinite Recursion Detected in Policy for Relation
Example error:
infinite recursion detected in policy
for relation "team_members"PostgreSQL may report error code 42P17.
This is especially common when designing team-based or organization-based RLS policies.
Why it happens
Imagine a team_members table that records which users belong to each team.
You create a policy on team_members that queries team_members to decide whether the user is allowed to view its rows.
PostgreSQL evaluates the policy.
The lookup triggers the same policy again.
That second evaluation triggers another evaluation, and the process cannot terminate normally.
Recursion can also happen indirectly when policies on two tables query one another.
How to fix it
Start by checking whether you can simplify the policy.
For example, if users only need to view their own membership records:
create policy "Users read own memberships"
on public.team_members
for select
to authenticated
using (
(select auth.uid()) = user_id
);This doesn't query team_members again from inside the policy.
For more complicated authorization requirements, a carefully reviewed SECURITY DEFINER function may be necessary.
However, do not blindly copy a privileged function from a forum.
A safe implementation needs:
- A trusted function owner.
- Restricted function execution privileges.
- A controlled
search_path. - Explicit caller identity checks.
- Careful review of which tables the function can access.
- Tests showing unauthorized users cannot use the helper to bypass authorization.
Where appropriate, keep helper functions in a private, non-API-exposed schema.
What to check
Inspect the policy definitions on the affected table and every related table referenced by those policies.
Look for circular dependencies rather than assuming the error comes from a slow query.
Related guide: Supabase Row Level Security Explained with Practical Examples
3. JWT Expired or Invalid Authentication Token
Example errors:
JWT expired401 UnauthorizedAuthentication tokens have limited lifetimes.
Supabase Auth uses access tokens and refresh tokens to manage sessions.
Why it happens
A user's access token may expire while the application remains open.
A properly configured Supabase client can refresh sessions when appropriate, but server-rendered applications need to handle cookies and token refresh correctly.
Problems may occur when:
- The application uses an outdated authentication integration.
- Server-side cookies aren't synchronized after a refresh.
- A refresh token is no longer valid.
- The browser and server use inconsistent authentication state.
- A protected request is sent without the expected access token.
How to fix it in Next.js
For applications using the App Router, use @supabase/ssr.
Install the required packages:
npm install @supabase/supabase-js @supabase/ssrCreate separate browser and server clients using Supabase's SSR documentation.
On Next.js 16, the request-level session refresh mechanism uses proxy.ts.
On Next.js 15 and earlier, the corresponding convention is middleware.ts.
The refresh helper should obtain verified claims:
const { data, error } = await supabase.auth.getClaims();
if (error || !data?.claims) {
// Handle an unauthenticated or invalid session.
}This is an excerpt from a broader SSR configuration, not a complete Proxy implementation.
The actual cookie adapter must correctly synchronize refreshed tokens between the request and response.
getClaims() versus getUser()
Use getClaims() when you need to verify identity from the access token.
Use getUser() when you need fresh user information from Supabase Auth.
Don't trust a cookie-derived session object from getSession() as your sole server-side authorization proof.
Important clarification
A JWT expiration error does not always mean the user must log in again.
It may indicate a missing or failed refresh mechanism.
Investigate the session lifecycle before treating every 401 response as an invalid password.
Related guide: Next.js Authentication Without NextAuth
4. JSON Object Requested, Multiple or No Rows Returned
Example error:
JSON object requested, multiple
(or no) rows returnedThis can occur when using Supabase's .single() method.
Why it happens
The .single() method expects exactly one row.
For example:
const { data, error } = await supabase
.from("profiles")
.select("*")
.eq("id", userId)
.single();If no matching row exists, the query can return an error.
If multiple rows match, it also violates the expected result shape.
How to fix it
Use .maybeSingle() when zero matching rows is a valid outcome.
const { data, error } = await supabase
.from("profiles")
.select("*")
.eq("id", userId)
.maybeSingle();
if (error) {
console.error(error.message);
} else if (data === null) {
console.log("Profile does not exist yet");
} else {
console.log(data);
}With .maybeSingle():
- One row returns an object.
- Zero rows returns
nullwithout treating absence as an error. - Multiple matching rows remain an error.
When should you keep .single()?
Use .single() when exactly one record must exist.
For example, after querying a database record by a unique ID, the absence of that record may indicate a real problem.
Check RLS before changing the query
Sometimes a row exists but the current user cannot see it because of RLS.
The API then behaves as though no accessible row was returned.
Don't immediately assume the database record is missing.
Verify authorization and row visibility using a properly authenticated test account.
Also check whether a missing uniqueness constraint is allowing multiple records where only one should exist.
5. Remaining Connection Slots Are Reserved
Example error:
remaining connection slots are reserved
for non-replication superuser connectionsThis indicates PostgreSQL cannot accept another ordinary connection because available connection capacity has been exhausted.
Why it happens
A serverless application can create many short-lived function instances.
If each instance opens multiple direct PostgreSQL connections, the total can grow quickly.
Connection-heavy workloads and long-running queries can make the problem worse.
This is especially relevant when using direct PostgreSQL drivers or ORMs.
How to fix it
Supabase offers several connection methods.
Use the method appropriate for your deployment environment.
For example:
- Direct connections: Often suitable for persistent backends when networking supports them.
- Session pooler: Useful when session-based connection behavior is required.
- Transaction pooler: Suitable for many serverless workloads with short-lived database operations.
For shared transaction pooling, the connection string typically uses port 6543.
Get the exact connection string from your Supabase project's Connect dialog.
Don't construct pooler hostnames manually.
Important: Transaction pooler limitations
Transaction pooling doesn't support every feature of a persistent PostgreSQL session.
Prepared statements and session-level state require special attention.
For example, when using Postgres.js with transaction pooling:
import postgres from "postgres";
export const sql = postgres(
process.env.DATABASE_URL!,
{
max: 1,
prepare: false,
ssl: "require",
}
);This example assumes a correctly configured transaction-pooler connection string and a compatible Postgres.js environment.
A production implementation should also review driver-specific transaction-pooling limitations.
What if you're using supabase-js?
If your application accesses the database through Supabase's REST API using supabase-js, you normally do not manage a separate direct PostgreSQL connection for those requests.
The connection-pooler configuration discussed here is primarily for applications using PostgreSQL connection strings through drivers and ORMs.
Don't replace your Supabase project URL with a PostgreSQL connection string.
6. Duplicate Key Value Violates Unique Constraint
Example error:
duplicate key value violates
unique constraint "profiles_pkey"PostgreSQL uses unique constraints to prevent duplicate records.
An insert fails when the new row conflicts with a unique or primary-key constraint.
Why it happens
Common causes include:
- Inserting the same record twice.
- Running a migration or seed script more than once.
- Creating profiles in both an authentication trigger and application code.
- Reusing an identifier that already exists.
- Retrying an operation without duplicate protection.
How to fix it
First, identify the constraint named in the error.
Then determine whether the application should insert a new record, update an existing one, or reject the duplicate.
If an update is appropriate, Supabase supports upserts:
const { data, error } = await supabase
.from("profiles")
.upsert(
{
id: userId,
full_name: "Example User",
},
{
onConflict: "id",
}
)
.select();
if (error) {
console.error(error.message);
}The example assumes the columns exist and the caller has the required database permissions.
Be careful with upserts
An upsert is not a universal fix.
It can overwrite an existing record if you send stale or incomplete data.
The caller also needs suitable RLS policies and grants for the operation's insert or update path.
If your signup process has a database trigger that automatically creates profiles, decide whether that trigger or your application should own profile creation.
Don't create two competing write paths without a clear reason.
What about API retries?
For payment, inventory, and order operations, use a deliberate idempotency strategy rather than relying only on generic upserts.
The correct behavior depends on the business operation.
7. Failed to Fetch After Deploying a Supabase App
Example error:
TypeError: Failed to fetchThis is a JavaScript network-level error, not a specific PostgreSQL error.
It can have several causes.
Common causes
- Incorrect Supabase project URL.
- Missing environment variables.
- DNS or network connectivity problems.
- An unavailable endpoint.
- Browser restrictions or extension interference.
- CORS configuration problems in a custom endpoint.
- An application attempting to call the wrong deployment environment.
How to diagnose it
Open the browser DevTools Network panel.
Find the failed request.
Check:
- The request URL.
- Whether an HTTP response was received.
- The browser console error.
- Whether the request is blocked or canceled.
- Whether the same request works in another environment.
Check Next.js environment variables
A typical browser-side Supabase setup needs:
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your-publishable-keyThese are placeholders.
In Vercel, configure the values for the correct Production or Preview environment.
For public Next.js environment variables, changes generally require a new build because their values can be included in the client bundle during compilation.
Don't expose private credentials
Never place Supabase service-role keys, secret keys, or database passwords in NEXT_PUBLIC_ variables.
If the failure is a CORS problem
Check whether you're calling a Supabase Edge Function, custom API endpoint, or third-party service.
The solution may require correct server-side CORS headers and preflight handling.
Don't disable browser security or add wildcard access rules without understanding which origins and credentials the endpoint should support.
Remember: A failed fetch doesn't automatically mean your RLS policy is wrong. RLS failures generally produce an API response with an error rather than a generic browser network failure.
8. Relation Does Not Exist
Example error:
relation "public.products" does not existPostgreSQL may report error code 42P01.
This happens when the database cannot find the referenced relation in the expected schema.
Why it happens
Possible causes include:
- The table was never created.
- A migration wasn't applied.
- You're connected to the wrong Supabase project.
- The table exists in a different PostgreSQL schema.
- The relation name has different capitalization.
- A function references an outdated table name.
How to fix it
First, confirm which database your application is using.
Check the Supabase URL and the deployed environment.
Then inspect the schema in the Supabase dashboard or through a trusted database session.
For a basic existence check:
select
to_regclass('public.products') as relation_name;If the result is null, the relation isn't present under that exact name in the connected database.
Use database migrations
Instead of manually recreating missing tables in production, keep schema changes in migration files.
For a Supabase CLI project, a new migration can be created using:
supabase migration new create_products_tableAfter reviewing the migration and confirming the intended linked project, you can apply pending migrations through the appropriate deployment workflow.
Safety note: Commands such as supabase db push can modify a linked database. Never run them against production casually or without reviewing pending changes and backups.
Distinguish database errors from API schema errors
An error saying a relation does not exist isn't the same as a PostgREST schema-cache error.
For example, an API may fail to recognize a recently created table or function even when PostgreSQL itself contains it.
In that case, check schema exposure and cache-related diagnostics rather than creating the same table again.
9. Column Reference Is Ambiguous
Example error:
column reference "id" is ambiguousPostgreSQL may return error code 42702.
Why it happens
This usually occurs when a query contains more than one possible source for a column name.
For example:
select id, name
from public.products
join public.order_items
on products.id = order_items.product_id;Both tables may contain an id column.
PostgreSQL can't determine which one you intended in the SELECT expression.
How to fix it
Use explicit table aliases and qualified column names.
select
p.id as product_id,
p.name,
oi.id as order_item_id
from public.products as p
join public.order_items as oi
on p.id = oi.product_id;Now each column has an unambiguous source.
Ambiguous names inside PostgreSQL functions
PL/pgSQL functions can also have naming conflicts.
For example, a local variable or function parameter might share a name with a table column.
A useful convention is to prefix function parameters:
create or replace function public.get_product_name(
p_product_id uuid
)
returns text
language sql
stable
as $$
select p.name
from public.products as p
where p.id = p_product_id;
$$;This avoids confusing a function parameter with products.id.
In larger functions, use explicit aliases consistently.
Don't fix ambiguity by renaming every database column
Clear query qualification is usually sufficient.
Changing a mature schema solely to remove ambiguous joins can create unnecessary migration work.
10. Supabase Authentication Emails Not Arriving
You create a signup form, users register, but confirmation emails never arrive.
Sometimes the frontend shows a successful request even though the intended email flow isn't completing as expected.
Common causes
- The project's default email provider is restricted.
- An email-sending rate limit was reached.
- The recipient isn't authorized for the built-in email service.
- Custom SMTP credentials are incorrect.
- Email authentication or domain configuration is incomplete.
- Messages are being filtered or rejected.
- Authentication redirect URLs are misconfigured.
Important: Supabase's default email service
Supabase's built-in SMTP service is intended primarily for testing and getting started.
Current documentation states that it is restricted to authorized recipients and subject to strict rate limits.
The documented default rate limit is 2 emails per hour, although platform limits may change.
That makes it unsuitable for most real public signup workflows.
How to fix it
For a production application that sends authentication emails, configure a supported custom SMTP provider.
Supabase supports SMTP-compatible email services.
Typical steps include:
- Choose an SMTP provider.
- Verify your sending domain.
- Configure the provider's SMTP credentials.
- Add those settings to Supabase Auth.
- Review the applicable email rate limits.
- Test signup and password-recovery emails.
- Verify confirmation links and redirect behavior.
Check more than email delivery
Receiving the message doesn't automatically mean the authentication flow is correct.
Open the confirmation link and verify that the application handles the token or code exchange successfully.
Also check that your configured redirect URLs match your deployed application.
For a Next.js SSR application, the confirmation callback must be implemented correctly.
Avoid exposing SMTP credentials
SMTP passwords and API credentials should remain in trusted configuration systems.
Never include them in public browser environment variables.
A Practical Supabase Troubleshooting Workflow
When you encounter an unfamiliar Supabase error, don't immediately change RLS or recreate database tables.
Start with the error details.
Step 1: Record the exact error
For database API calls, log the safe diagnostic fields:
const { data, error } = await supabase
.from("products")
.select("id, name")
.limit(10);
if (error) {
console.error({
code: error.code,
message: error.message,
details: error.details,
hint: error.hint,
});
}Use this diagnostic pattern in an appropriate development or trusted server environment. Redact sensitive values before sending logs to external monitoring services.
The error code is often more useful than the generic message displayed by the application.
Step 2: Identify the failing component
Determine whether the error comes from:
- PostgreSQL
- PostgREST
- Supabase Auth
- The browser network layer
- A Supabase Edge Function
- A direct database connection
Don't assume all Supabase errors have the same cause.
Step 3: Check authentication and permissions
If the request is user-specific, verify that it uses the expected authenticated session.
For database operations, review both grants and RLS policies.
Don't switch to a service-role key merely to make an authorization error disappear.
Step 4: Compare local and deployed environments
Check the project URL, environment variables, database schema, migrations, and package versions.
Avoid printing secret values.
Step 5: Reproduce the issue safely
Use a disposable development project or controlled test data.
For authorization problems, test with at least two independent user identities.
For connection failures, inspect actual connection counts and driver configuration.
Step 6: Apply the smallest correct fix
Change the policy, query, session handling, or configuration responsible for the failure.
Avoid broad changes that accidentally weaken security.
Step 7: Verify the outcome
Repeat the operation that previously failed.
Also check that unauthorized operations are still denied and that the change didn't introduce another regression.
Verification note: The examples in this guide describe documented error patterns and expected solutions. They are not presented as incidents personally reproduced in production. Exact SQL, permissions, connection settings, and authentication flows should be tested in the relevant environment before use.
Supabase Production Readiness Checklist
Before launching a Supabase-backed application, review the following areas.
Database security
- RLS enabled on tables exposed through APIs.
- Appropriate table grants and policies.
- No unnecessary anonymous access.
- No secret or service-role keys exposed in browser code.
- Security-sensitive functions reviewed.
Authentication
- Cookie-based SSR configuration where needed.
- Reliable session refresh.
- Tested signup, login, logout, and password recovery.
- Working confirmation redirects.
- Production-ready email delivery.
Database reliability
- Appropriate connection method for the runtime.
- Reviewed migration process.
- Useful indexes for common queries.
- Monitoring of slow queries and connection limits.
- Safe backup and recovery procedures.
Application quality
- Environment variables configured for each deployment.
- Useful, non-sensitive error logging.
- Proper handling of empty database results.
- Idempotent behavior where retries can create duplicates.
- Tests for unauthorized access and common failure conditions.
Final Thoughts
Supabase simplifies many parts of application development, but production reliability still depends on understanding how PostgreSQL, authentication, and the API layer work together.
A Row Level Security violation is fundamentally different from an expired JWT.
A database connection limit requires a different solution from a missing migration.
And a failed network request doesn't necessarily mean the database rejected your query.
The most useful troubleshooting habit is to identify the error's source before attempting a fix.
Start with the error code, inspect the relevant configuration, reproduce the failure safely, and verify that your changes solve the problem without weakening security.
Reliable Supabase applications aren't built by avoiding every error. They're built by making failures understandable, recoverable, and testable.
Related CodeWithLogs Guides
- Supabase Row Level Security Explained with Practical Examples
- Next.js Authentication Without NextAuth
- Build an Inventory Management System with Next.js and Supabase
- Common Vercel Deployment Errors
- Error Decoder Tool
Official Documentation
Keep the conversation useful
Found a different result?
Include your framework version, the error, and the steps to reproduce it. Specific details help improve the article for the next reader.
Send a correction or question

