Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

docs(troubleshooting): add soft delete article (#36121)

Charisa1376940c93f
diff --git a/apps/docs/content/troubleshooting/database-api-42501-errors.mdx b/apps/docs/content/troubleshooting/database-api-42501-errors.mdx
new file mode 100644
index 00000000000..a0c651bf909
--- /dev/null
+++ b/apps/docs/content/troubleshooting/database-api-42501-errors.mdx
@@ -0,0 +1,69 @@
+---
+title = "Database API 42501 errors"
+topics = [
+"database"
+]
+github_url = "https://github.com/orgs/supabase/discussions/31293"
+
+[[errors]]
+http_status_code = 401
+code = "42501"
+
+[[errors]]
+http_status_code = 403
+code = "42501"
+---
+
+[Postgres 42501 errors](https://www.postgresql.org/docs/current/errcodes-appendix.html), often reported by clients as 401 or 403 errors, imply the request lacked adequate privileges. They can be viewed in the [log explorer](https://supabase.com/dashboard/project/_/logs/explorer?q=select%0A++++cast%28postgres_logs.timestamp+as+datetime%29+as+timestamp%2C%0A++++event_message%2C%0A++++parsed.error_severity%2C%0A++++parsed.user_name%2C%0A++++parsed.query%2C%0A++++parsed.detail%2C%0A++++parsed.hint%2C%0A++++parsed.sql_state_code%2C%0A++++parsed.backend_type%0Afrom%0A++++postgres_logs%0A++++cross+join+unnest%28metadata%29+as+metadata%0A++++cross+join+unnest%28metadata.parsed%29+as+parsed%0Awhere%0A++++parsed.sql_state_code+%3D+%2742501%27%0Aorder+by%0A++++timestamp+desc%0Alimit+100%3B%0A) by running:
+
+```sql
+select
+ cast(postgres_logs.timestamp as datetime) as timestamp,
+ event_message,
+ parsed.error_severity,
+ parsed.user_name,
+ parsed.query,
+ parsed.detail,
+ parsed.hint
+from
+ postgres_logs
+ cross join unnest(metadata) as metadata
+ cross join unnest(metadata.parsed) as parsed
+where
+ regexp_contains(parsed.error_severity, 'ERROR|FATAL|PANIC')
+ and parsed.sql_state_code = '42501'
+order by timestamp desc
+limit 100;
+```
+
+They tend to be caused by one of the following factors.
+
+### Attempted to access a forbidden schema
+
+API roles cannot access certain schemas, most notably `auth` and `vault`. This restriction extends to Foreign Data Wrappers relying on `vault`. While you can bypass it using a [security definer function](https://supabase.com/docs/guides/database/functions?queryGroups=language&language=sql&queryGroups=example-view&example-view=sql#security-definer-vs-invoker), these schemas are intentionally restricted for security reasons.
+
+### Attempted to access a custom schema
+
+If you created a custom schema, you will have to give the Database API permission to query it. Follow our [Using Custom Schemas guide](https://supabase.com/docs/guides/api/using-custom-schemas) for more directions.
+
+### Revoked object level access:
+
+In rare cases, users may accidentally revoke object-level access in `public` from their API roles. To regrant full visibility, run the below code:
+
+```sql
+grant usage on schema public to anon, authenticated, service_role;
+grant all on all tables in schema public to anon, authenticated, service_role;
+grant all on all routines in schema public to anon, authenticated, service_role;
+grant all ON all sequences in schema public to anon, authenticated, service_role;
+alter default privileges for role postgres in schema public grant all on tables to anon, authenticated, service_role;
+alter default privileges for role postgres in schema public grant all on routines to anon, authenticated, service_role;
+alter default privileges for role postgres in schema public grant all on sequences to anon, authenticated, service_role;
+```
+
+### Configured column-level restrictions
+
+If you've set column-based access in the [Dashboard](https://supabase.com/dashboard/project/_/database/column-privileges) or via SQL, queries will fail with a `42501` error when accessing restricted columns. This includes using `select *`, as it expands to include forbidden columns.
+
+### RLS:
+
+If the anon or authenticated roles attempt to UPDATE or INSERT values without the necessary RLS permissions, Postgres will return a 42501 error.
diff --git a/apps/docs/content/troubleshooting/soft-deletes-with-supabase-js.mdx b/apps/docs/content/troubleshooting/soft-deletes-with-supabase-js.mdx
new file mode 100644
index 00000000000..9e85ed8de16
--- /dev/null
+++ b/apps/docs/content/troubleshooting/soft-deletes-with-supabase-js.mdx
@@ -0,0 +1,107 @@
+---
+title = "Implementing soft deletes with supabase-js"
+topics = []
+keywords = ["supabase-js", "sdk", "javascript"]
+github_url="https://github.com/orgs/supabase/discussions/32523"
+---
+
+When building modern applications, soft deletes are a common feature that lets you "delete" data while retaining it for potential recovery or historical tracking. This is especially useful in audit trails or when accidental deletions need undoing. Supabase makes this process seamless with Postgres views and the supabase-js library.
+
+In this post, we’ll show how to implement soft deletes using Supabase and how to use Postgres views to manage your data efficiently.
+
+## What are soft deletes?
+
+Soft deletes don’t remove a record from the database. Instead, they mark it as "deleted" by updating a specific column, often named `deleted_at`, with a timestamp. This keeps the data in the database but excludes it from most queries unless explicitly required.
+
+## Step 1: Add the `deleted_at` column
+
+To implement soft deletes, start by adding a `deleted_at` column to your table.
+
+Run this SQL in your Supabase SQL editor:
+
+```sql
+alter table items
+add column deleted_at timestamptz;
+```
+
+This column will store the timestamp when a record is "deleted."
+
+## Step 2: Create a view for active records
+
+To ensure you only fetch non-deleted records by default, create a Postgres view that filters out rows where `deleted_at` is not null.
+
+```sql
+create view active_items as
+ select *
+ from items
+ where deleted_at is null;
+```
+
+With this view, you can now query `active_items` instead of `items` to get only active (non-deleted) rows.
+
+## Step 3: Soft delete a record
+
+Instead of deleting a record, update its `deleted_at` column with the current timestamp. Using `supabase-js`, it looks like this:
+
+```javascript
+await supabase.from('items').update({ deleted_at: new Date().toISOString() }).eq('id', 123)
+```
+
+This sets the `deleted_at` column for the item with `id` 123.
+
+## Step 4: Query active records
+
+To fetch only non-deleted rows, query the `active_items` view instead of the `items` table. Here's how you do it with `supabase-js`:
+
+```javascript
+const { data, error } = await supabase
+ .from('active_items') // Query the view, not the table
+ .select('*')
+
+if (error) console.error('Error fetching active items:', error)
+else console.log('Active items:', data)
+```
+
+## Step 5: Restore a soft-deleted record (optional)
+
+To "restore" a soft-deleted record, set the `deleted_at` column back to `null`:
+
+```javascript
+await supabase.from('items').update({ deleted_at: null }).eq('id', 123)
+```
+
+This effectively un-deletes the record.
+
+## Benefits of using views for soft deletes
+
+- **Cleaner Queries:** No need to add `WHERE deleted_at IS NULL` to every query. Just query the view (`active_items`).
+- **Separation of Concerns:** Views abstract the logic of filtering deleted records from your application code.
+- **Efficiency:** Postgres handles the filtering in the view, reducing the complexity in your app.
+
+## Full example with supabase-js
+
+Here’s a complete example of implementing soft deletes with `supabase-js`:
+
+```javascript
+// 1. Soft delete an item
+await supabase.from('items').update({ deleted_at: new Date().toISOString() }).eq('id', 123)
+
+// 2. Query active (non-deleted) items
+const { data, error } = await supabase
+ .from('active_items') // Query the view, not the table
+ .select('*')
+
+if (error) console.error('Error fetching active items:', error)
+else console.log('Active items:', data)
+
+// 3. Restore a soft-deleted item
+await supabase.from('items').update({ deleted_at: null }).eq('id', 123)
+```
+
+---
+
+## Conclusion
+
+Soft deletes are easy to implement with Supabase and Postgres. By combining a `deleted_at` column with views, you can cleanly separate active and deleted records, keeping your application logic simple and maintainable.
+
+This approach provides the flexibility of retaining data for audits or recovery while keeping your app's interface clean and efficient. Start using soft deletes in your Supabase projects today!