Помогает избежать 12 частых ошибок Supabase при ревью и отладке.

Звёзды2 926
Авторjeremylongshore
Установок33

Установка

SKILL.md

Supabase Known Pitfalls

Overview

The twelve most common Supabase mistakes, ranked by severity: security (service_role exposure, missing RLS, permissive policies, no connection pooling), data integrity (ignoring { data, error }, missing .select() after mutations, .single() on optional results), and performance / maintainability (select('*'), N+1 queries, missing FK indexes, multiple client instances, no generated types). Each pitfall shows the broken code, why it fails, and the correct pattern using createClient from @supabase/supabase-js.

This SKILL.md carries the full pitfall table plus one representative fix per category. The verbatim broken-vs-correct code and detection queries for all twelve live in references/pitfalls.md — drill in there for depth.

Prerequisites

  • Access to a Supabase project codebase for review
  • @supabase/supabase-js v2+ installed
  • Basic understanding of Row Level Security (RLS)

Instructions

Work the pitfalls top-down by severity. Fix every Critical finding before moving on — a single security miss can expose the whole database.

#PitfallSeverityFix
1service_role key in client bundleCriticalanon key on client; service_role server-only, no NEXT_PUBLIC_
2Table without RLSCriticalALTER TABLE … ENABLE ROW LEVEL SECURITY right after CREATE TABLE
3Overly permissive RLS policyCriticalscope USING (…) to auth.uid(), never USING (true) for writes
4No connection pooling in serverlessCriticalpooled string (Supavisor, port 6543), not the direct 5432 URL
5Ignoring { data, error }Highdestructure both; check error before touching data
6Missing .select() after mutationHighchain .select('cols') — mutations return null otherwise
7.single() on optional resultHighuse .maybeSingle() for 0-or-1; .single() only for guaranteed 1
8select('*') everywhereMediumname the columns — smaller payload, typed, no leakage
9N+1 query loopMediumPostgREST embedded join, or batch with .in()
10FK column without indexMediumCREATE INDEX on every foreign-key column
11Multiple client instancesLowsingleton in lib/supabase.ts, imported everywhere
12Hand-written DB typesLowsupabase gen types typescript --linked

Step 1 — Security (Critical, pitfalls 1-4)

The service_role key bypasses all RLS, so it must never reach a browser bundle. Split the client by trust boundary:

// Client (browser): anon key — respects RLS
const supabase = createClient(url, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!)

// Server only (API routes, server actions): service_role, NO NEXT_PUBLIC_ prefix
const supabaseAdmin = createClient(url, process.env.SUPABASE_SERVICE_ROLE_KEY!,
  { auth: { autoRefreshToken: false, persistSession: false } })

Then confirm RLS is enabled on every table, tighten any USING (true) policy to auth.uid(), and use the pooled connection string in serverless. Full broken-vs-correct code and the SQL detection queries for pitfalls 1-4 are in the Security section of references/pitfalls.md.

Step 2 — Data Integrity (High, pitfalls 5-7)

Supabase returns { data, error } and mutations return null unless you ask for the row back:

const { data, error } = await supabase
  .from('orders').insert(order)
  .select('id, status')   // without .select(), data is null
  .maybeSingle()          // .single() throws PGRST116 on 0 rows
if (error) throw new Error(`Order failed: ${error.message}`)

See the Data Integrity section of references/pitfalls.md for the .single() vs .maybeSingle() rule of thumb and each failure mode.

Step 3 — Performance & Maintainability (Medium/Low, pitfalls 8-12)

Name your columns, collapse N+1 loops into a single embedded join, index foreign keys, share one client instance, and use generated types:

// One query instead of 1 + N — PostgREST embeds the FK relation
const { data } = await supabase
  .from('projects')
  .select('id, name, tasks (id, title, status)')

The full singleton pattern, the FK-index detection query, and the supabase gen types workflow are in the Performance and Maintainability section of references/pitfalls.md.

Output

  • Security pitfalls identified: service_role exposure, missing RLS, permissive policies, no connection pooling
  • Data integrity pitfalls fixed: { data, error } handling, .select() after mutations, .maybeSingle() usage
  • Performance pitfalls resolved: column-specific selects, JOIN queries, FK indexes
  • Maintainability improved: singleton client, generated types
  • Detection commands for automated scanning of each pitfall

Error Handling

IssueCauseSolution
PGRST116: JSON object requested, multiple (or no) rows returnedUsed .single() when 0 or 2+ rows matchUse .maybeSingle() for optional lookups
data is null after insertMissing .select() chainAdd .select('column1, column2') after .insert()
TypeError: Cannot read property of nullDestructured only data, ignoring errorAlways destructure { data, error } and check error first
too many connections for roleDirect connection from serverlessUse pooled connection string (port 6543)
permission denied for tableRLS blocking access, no matching policyCheck RLS policies match the authenticated user's JWT claims
relation does not existTable name typo, not caught at compile timeUse generated types for compile-time validation

More operator-facing failure modes (legacy codebases, false positives, fixes that break tests): references/errors.md.

Examples

Quick Security Audit

# Check for the three critical code-level security pitfalls in one pass
echo "=== Pitfall 1: Service role in client code ==="
grep -rn 'SERVICE_ROLE' --include="*.tsx" --include="*.ts" src/ app/ components/ 2>/dev/null || echo "Clean"

echo "=== Pitfall 2: Tables without RLS (run in SQL Editor) ==="
echo "SELECT tablename FROM pg_tables WHERE schemaname='public' AND rowsecurity=false;"

echo "=== Pitfall 3: Overly permissive policies (run in SQL Editor) ==="
echo "SELECT tablename, policyname FROM pg_policies WHERE qual='true' AND cmd!='r';"

Code Review Checklist

### Security
- [ ] No SERVICE_ROLE_KEY in client-side code or NEXT_PUBLIC_* vars
- [ ] RLS enabled on all new tables; policies scope to auth.uid() (no USING(true) writes)
### Data Integrity
- [ ] All calls destructure { data, error } and check error
- [ ] .select() chained after insert/update/upsert; .maybeSingle() for optional lookups
### Performance & Maintainability
- [ ] Columns named in .select() (no select('*')); no N+1; FK columns indexed
- [ ] Single createClient instance; generated types; pooled connection string in serverless

More detection one-liners: references/examples.md. Every pitfall's full before/after code: references/pitfalls.md.

Resources

  • Supabase Auth: Securing Your Data
  • Row Level Security
  • TypeScript Support
  • Connection Pooling
  • Supabase JavaScript Client Reference
  • PostgREST Error Codes

Next Steps

This completes the Supabase pitfalls reference. To start a new project with best practices from day one, see supabase-hello-world.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: supabase-known-pitfalls](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-supabase-known-pitfalls)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
225 587 ★
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.
225 587 ★
Kotlin Revieweraffaan-m · Ревьюер Kotlin и Android/KMP: корутины, Compose, архитектура и типичные ошибки.
225 587 ★
Projectsaffaan-m · Перечисляет известные проекты и статистику их инстинктов.
225 587 ★
Vue Revieweraffaan-m · Ревьюер Vue.js: Composition API, реактивность, архитектура компонентов, Pinia, Nuxt.
225 587 ★
supabaseanthropics · Интеграция Supabase MCP для работы с базой данных, аутентификации, хранилища и подписок в…
100 комп.
Oracle-to-PostgreSQL Migration Expertgithub · Агент для миграции приложений с Oracle на PostgreSQL. Обучает пользователей концепциям…
36 140 ★
zero-hallucination-coderalirezarezvani · Дисциплинированный конвейер кодинга: Discuss → Map → Decompose → Execute → Verify с…
510 комп.
agent-linkanthropics · Навыки для создания full-stack приложений на Supabase: схемы, миграции, RPC-first доступ…
38 комп.
claude-etaanthropics · Трекер и оценщик длительности задач для Claude Code. Незаметно замеряет время каждой…
38 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8