supabase-security-basics
Applies security best practices to Supabase, including RLS policy enforcement, secret management, and API key separation.
Install
mkdir -p .claude/skills/supabase-security-basics && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/7937" && unzip -o skill.zip -d .claude/skills/supabase-security-basics && rm skill.zipInstalls to .claude/skills/supabase-security-basics
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Apply Supabase security best practices: anon vs service_role key separation,Key capabilities
- →Separate anon and service_role key usage
- →Implement policy patterns for user-specific data access
- →Configure role-based access via custom JWT claims
- →Harden API surface against unauthorized access
How it works
It enforces security by strictly separating public-facing anon keys from administrative service_role keys and applying RLS policies to restrict database access.
Inputs & outputs
When to use supabase-security-basics
- →Configuring anon and service_role keys correctly
- →Implementing RLS policies for table security
- →Performing a production security audit
- →Securing API endpoints
About this skill
Supabase Security Basics
Overview
The Data API exposes configured schemas through PostgREST. Access depends on schema exposure, the requesting role’s object grants, and RLS policies; a non-RLS table is not automatically readable and writable without grants. This skill covers the three pillars of Supabase security: key separation (anon vs service_role), RLS policy enforcement, and API surface hardening.
Prerequisites
- Supabase project created (local or hosted) with Dashboard access
@supabase/supabase-jsinstalled (npm install @supabase/supabase-js)SUPABASE_URLandSUPABASE_ANON_KEYenvironment variables configured- Basic understanding of SQL and Postgres
Instructions
Step 1 — Understand the Two API Keys
Distinguish public and privileged keys. The table below describes legacy JWT-based keys; current projects also support publishable and secret keys, with different rotation and verification behavior:
| Key | Environment Variable | Exposed to Client? | RLS Behavior |
|---|---|---|---|
| Anon key | SUPABASE_ANON_KEY | Yes — browser-safe | Respects all RLS policies |
| Service role key | SUPABASE_SERVICE_ROLE_KEY | NEVER expose | Bypasses ALL RLS |
The anon key is a JWT that PostgREST uses to determine which RLS policies apply. It may be included in client-side bundles; the effective role still needs appropriate grants and RLS on exposed tables. A public key does not identify a signed-in user. The service role key bypasses every RLS policy and should only ever exist in server-side code (API routes, Edge Functions, cron jobs, migration scripts).
// CORRECT: anon key on the client
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
// CORRECT: service role key ONLY in server-side code
// e.g., app/api/admin/route.ts (Next.js server route)
import { createClient } from '@supabase/supabase-js'
const supabaseAdmin = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!,
{ auth: { autoRefreshToken: false, persistSession: false } }
)
// WRONG — service role key in client-side code
// This bypasses ALL RLS and leaks your admin key to every user
const supabase = createClient(url, process.env.NEXT_PUBLIC_SERVICE_ROLE_KEY!) // NEVER DO THIS
Key rotation: Inventory legacy JWT keys, publishable/secret API keys, and Auth signing keys separately. Follow the current API-key migration and signing-key procedures for the actual key type. Stage and verify consumer cutover, then explicitly revoke/deactivate the retired credential as supported. Coexistence, caching, signing-key grace periods, and already-issued JWT lifetime differ; do not promise universal immediate invalidation or zero grace. Never print keys during verification.
Step 2 — Enforce Row Level Security on Every Table
Audit configured exposed schemas and grants as well as RLS. Non-RLS tables can expose rows to roles granted access; enabling RLS constrains ordinary roles but does not constrain a superuser, BYPASSRLS role, or normally the table owner. Test the actual request role and identity.
-- Audit: find tables missing RLS
SELECT schemaname, tablename, rowsecurity
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY tablename;
-- Enable RLS on every public table
ALTER TABLE public.users ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.todos ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
-- With no applicable policies, ordinary RLS-constrained roles are denied.
-- Grant and add policies ONLY for reviewed required operations. SELECT-only
-- access does not require INSERT/UPDATE/DELETE policies; keep writes denied.
Policy patterns — independently reviewed operations:
The following policies are alternatives to adopt only for required operations, not a mandate to enable every write. Review existing permissive policies and grants first; a policy alone does not grant table privileges.
-- SELECT: user can only read their own rows
CREATE POLICY "Users read own data"
ON public.todos FOR SELECT
USING (auth.uid() = user_id);
-- INSERT: user can only insert rows for themselves
CREATE POLICY "Users insert own data"
ON public.todos FOR INSERT
WITH CHECK (auth.uid() = user_id);
-- UPDATE: user can only update their own rows
CREATE POLICY "Users update own data"
ON public.todos FOR UPDATE
USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);
-- DELETE: user can only delete their own rows
CREATE POLICY "Users delete own data"
ON public.todos FOR DELETE
USING (auth.uid() = user_id);
Policy pattern — public read, authenticated write:
CREATE POLICY "Anyone can read posts"
ON public.posts FOR SELECT
USING (true);
CREATE POLICY "Authenticated users can insert"
ON public.posts FOR INSERT
WITH CHECK (auth.uid() IS NOT NULL);
Policy pattern — role-based access via custom JWT claims:
-- Admin-only policy using app_metadata
CREATE POLICY "Admins have full access"
ON public.settings FOR ALL
USING (
(auth.jwt() -> 'app_metadata' ->> 'role') = 'admin'
);
To set custom claims server-side:
// Server-side only — requires service role key
const { error } = await supabaseAdmin.auth.admin.updateUserById(userId, {
app_metadata: { role: 'admin' }
})
Policy pattern — organization-scoped access:
CREATE POLICY "Org members can read projects"
ON public.projects FOR SELECT
USING (
EXISTS (
SELECT 1 FROM public.members
WHERE members.organization_id = projects.organization_id
AND members.user_id = auth.uid()
)
);
Key distinction — USING vs WITH CHECK:
USING (expr)— filters which existing rows the user can see (SELECT, UPDATE, DELETE)WITH CHECK (expr)— validates new/modified row data (INSERT, UPDATE)- For UPDATE, you need both: USING controls which rows can be targeted, WITH CHECK controls what the new values can be
Step 3 — Harden the API Surface
JWT verification: Supabase verifies JWTs server-side automatically. The auth.uid() function in RLS policies extracts the authenticated user's ID from the verified JWT. You do not need to verify tokens manually in RLS policies — Supabase handles this.
SQL injection prevention: The Supabase JS SDK uses parameterized queries internally. Never build raw SQL strings from user input — always use the SDK query builder:
// SAFE: SDK parameterizes automatically
const { data } = await supabase
.from('posts')
.select('*')
.eq('author_id', userId)
.ilike('title', `%${searchTerm}%`)
// DANGEROUS: raw SQL with string interpolation
// Only use supabase.rpc() with parameterized functions, never template literals
Network restrictions: Restrict direct database connections to known IP ranges in Dashboard > Settings > Database > Network Restrictions. This does not affect the REST API (which goes through PostgREST) but protects direct Postgres connections.
CORS boundary: For browser calls to an Edge Function, implement the documented function CORS/preflight handling and the application’s reviewed origin policy. This is not a universal Data API Dashboard CORS setting. Auth redirect allowlists are a separate control. Origins and preflight responses are not authentication or row authorization; retain verified identity, grants, and RLS.
Disable unused auth providers: Dashboard > Authentication > Providers. Disable any provider you are not actively using (email, phone, Google, GitHub, etc.) to reduce attack surface.
SSL enforcement: Dashboard > Settings > Database > SSL Configuration. Enforce SSL for all direct database connections.
Statement timeouts: Prevent long-running queries from exhausting database resources:
ALTER ROLE authenticated SET statement_timeout = '10s';
ALTER ROLE anon SET statement_timeout = '5s';
Revoke default schema grants (verify only):
-- Supabase handles this by default, but verify:
-- anon and authenticated roles should only access data through RLS policies
SELECT grantee, privilege_type, table_name
FROM information_schema.role_table_grants
WHERE table_schema = 'public'
AND grantee IN ('anon', 'authenticated')
ORDER BY table_name, grantee;
Output
After completing these steps you will have:
- Anon key used exclusively in client-side code, service role key restricted to server-side
- RLS enabled on every public table with explicit policies per operation
- Custom JWT claims configured for role-based access patterns
- Network restrictions, CORS, SSL, and statement timeouts hardened
- Unused auth providers disabled
Security Audit Checklist
- RLS enabled on ALL public tables (
SELECT rowsecurity FROM pg_tables WHERE schemaname='public') - Every table has at least one RLS policy per needed operation
- Service role key is NOT in any client-side or
NEXT_PUBLIC_*environment variables -
.envfiles are in.gitignore - Email confirmation enabled (Dashboard > Authentication > Settings)
- OAuth redirect URLs restricted to your domains
- Unused auth providers disabled
- SSL enforcement enabled (Dashboard > Database > SSL)
- Database password changed from default
- Network restrictions configured for direct DB connections
-
statement_timeoutset forauthenticatedandanonroles - MFA enabled for sensitive user operations
- Point-in-time recovery (PITR) enabled for production
- API keys rotated after any suspected exposure
Error Handling
| Error | Cause | Solution |
|---|---|---|
| `42501: new row violates row-level sec |
Content truncated.
When not to use it
- →When exposing the service_role key to client-side code
Prerequisites
Limitations
- →Enabling RLS with no policies blocks all API access
- →auth.uid() only works in RLS policies evaluated by PostgREST
How it compares
It moves beyond default open access by requiring explicit RLS policies for every database operation.
Compared to similar skills
supabase-security-basics side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| supabase-security-basics (this skill) | 0 | 4mo | Review | Intermediate |
| reverse-engineering-tools | 73 | 7mo | No flags | Advanced |
| game-hacking-techniques | 42 | 6mo | No flags | Advanced |
| solidity-security | 15 | 6mo | No flags | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by jeremylongshore
View all by jeremylongshore →You might also like
reverse-engineering-tools
gmh5225
Guide for reverse engineering tools and techniques used in game security research. Use this skill when working with debuggers, disassemblers, memory analysis tools, binary analysis, or decompilers for game security research.
game-hacking-techniques
gmh5225
Guide for game hacking techniques and cheat development. Use this skill when researching memory manipulation, code injection, ESP/aimbot development, overlay rendering, or game exploitation methodologies.
solidity-security
wshobson
Master smart contract security best practices to prevent common vulnerabilities and implement secure Solidity patterns. Use when writing smart contracts, auditing existing contracts, or implementing security measures for blockchain applications.
1password
openclaw
Set up and use 1Password CLI (op). Use when installing the CLI, enabling desktop app integration, signing in (single or multi-account), or reading/injecting/running secrets via op.
senior-security
davila7
Comprehensive security engineering skill for application security, penetration testing, security architecture, and compliance auditing. Includes security assessment tools, threat modeling, crypto implementation, and security automation. Use when designing security architecture, conducting penetration tests, implementing cryptography, or performing security audits.
ghidra
mitsuhiko
Reverse engineer binaries using Ghidra's headless analyzer. Decompile executables, extract functions, strings, symbols, and analyze call graphs without GUI.