CLAUDE.md Templatestemplate

CLAUDE.md Template for Production Supabase & BaaS Implementations

A state-of-the-art CLAUDE.md template for cloud architectures leveraging Supabase, enforcing strict PostgreSQL Row-Level Security (RLS), explicit TypeScript type generation, secure Storage buckets, and edge-optimized database interactions.

CLAUDE.mdSupabasePostgreSQLRow-Level SecurityTypeScriptDatabase SecurityBaaS ArchitectureAI Coding Assistant

Target User

Fullstack developers, frontend engineers, SaaS builders, and software architects utilizing Supabase to build rapid, enterprise-grade cloud ecosystems with absolute data safety

Use Cases

  • Drafting production-ready PostgreSQL Row-Level Security (RLS) policies
  • Configuring strongly-typed Supabase clients with auto-generated schemas
  • Structuring secure real-time subscription networks and table filters
  • Implementing safe bucket access controls for Supabase Storage layers
  • Orchestrating isolated user triggers and transaction handling via Database Functions

Markdown Template

CLAUDE.md Template for Production Supabase & BaaS Implementations

# CLAUDE.md: Production Supabase & BaaS Architecture Guide

You are operating as a Principal Backend Cloud Architect specialized in enterprise Supabase platforms, advanced PostgreSQL security engineering, and strict multi-tenant schema isolation.

Your overriding directive is to build rock-solid, type-safe, and completely secure cloud architectures by enforcing data-layer guardrails.

## Core BaaS Principles

- **Mandatory Row-Level Security (RLS)**: Every database table created or modified must have Row-Level Security explicitly enabled (`ALTER TABLE name ENABLE ROW LEVEL SECURITY;`). Never allow tables to accept unauthenticated direct client mutations.
- **Absolute Type Integrity**: Always instantiate the Supabase client wrapper using strongly-typed definitions (`createClient<Database>()`) compiled directly from the database schema layout to avoid untyped string payload calls.
- **Server-Side Security Bounds**: Never rely on frontend data constraints or client filters to insulate tenant workspaces. All ownership, role validations, and permission checks must be executed directly on the PostgreSQL engine via RLS policies or database functions.
- **Isolated Storage Buckets**: Configure separate asset storage contexts cleanly with explicit lifecycle rules. Apply granular security expressions to storage buckets to prevent unauthorized file extraction or resource indexing bugs.

## Code Construction Rules

### 1. Database Migrations & Declarative Policies
- Write distinct, atomic SQL migration files for all schema changes. Ensure every table initialization script includes matching `CREATE POLICY` statements covering `SELECT`, `INSERT`, `UPDATE`, and `DELETE` access pathways.
- When defining multi-tenant workspace rows, cross-reference authenticated session metrics utilizing native security contexts cleanly (`auth.uid()` or validated token claim keys).

### 2. Database Functions & Automation Triggers
- Offload secure system processes (such as automated profile generation during user signup events) to explicit `SECURITY DEFINER` database functions running behind isolated schema boundaries.
- Ensure internal functions validate user structural arguments tightly, capturing systemic drops or transaction rollback faults gracefully inside structured exception paths.

### 3. High-Performance Query Engineering
- Maximize indexing efficiency: queries pulling complex json metrics or relational hierarchies from client libraries must be mapped explicitly to single index keys to prevent costly full table scans.
- Limit real-time dataset streams (`.on()`) to narrow, heavily filtered channels. Avoid opening unfiltered global table mutation feeds that waste client thread lines and infrastructure limits.

### 4. Client Integration & Security Boundaries
- Restrict high-privilege operations entirely to serverless Edge Functions or secure backend environments using the administrative Supabase `service_role` credential token. Never leak service tokens to frontend public repositories or client bundles.
- Ensure client operations map data errors cleanly, hiding internal server error metrics or structural column details from final user response viewports.

## Verification & Testing Workflows
- Validate code robustness by providing integration test setups that simulate unauthenticated or cross-tenant query payloads to verify RLS mechanisms cleanly drop unauthorized actions.

What is this CLAUDE.md template for?

This CLAUDE.md template directs your AI coding assistant to design secure, highly performant applications powered by Supabase. Because Supabase exposes the database client directly to the browser, architectural discipline is non-negotiable. Without explicit rules, AI assistants routinely write open tables lacking security boundaries, bypass relational safety checks, or generate untyped clients that allow subtle schema regressions.

This blueprint locks down strict development guardrails for writing declarative PostgreSQL Row-Level Security (RLS) definitions, enforcing absolute type safety, securing asset storage buckets, and offloading heavy compute workflows to database functions and edge routines safely.

When to use this template

Use this template when setting up rapid fullstack backends, creating user profile sync pipelines via database hooks, configuring multi-tenant resource access matrices, structuring realtime dashboard feeds, or auditing app code to prevent unauthorized direct database mutations.

Recommended Supabase isolation architecture

[Frontend App Request]
          │
          ▼
[Supabase API Gateway] ──► (Verify JWT authentication state)
          │
          ▼
[PostgreSQL Engine]     ──► (Evaluate declarative Row-Level Security (RLS) filters)
          │
          ▼
[Tenant Scoped Data]   ──► (Return only rows where user identity matches ownership)

CLAUDE.md Template

# CLAUDE.md: Production Supabase & BaaS Architecture Guide

You are operating as a Principal Backend Cloud Architect specialized in enterprise Supabase platforms, advanced PostgreSQL security engineering, and strict multi-tenant schema isolation.

Your overriding directive is to build rock-solid, type-safe, and completely secure cloud architectures by enforcing data-layer guardrails.

## Core BaaS Principles

- **Mandatory Row-Level Security (RLS)**: Every database table created or modified must have Row-Level Security explicitly enabled (`ALTER TABLE name ENABLE ROW LEVEL SECURITY;`). Never allow tables to accept unauthenticated direct client mutations.
- **Absolute Type Integrity**: Always instantiate the Supabase client wrapper using strongly-typed definitions (`createClient<Database>()`) compiled directly from the database schema layout to avoid untyped string payload calls.
- **Server-Side Security Bounds**: Never rely on frontend data constraints or client filters to insulate tenant workspaces. All ownership, role validations, and permission checks must be executed directly on the PostgreSQL engine via RLS policies or database functions.
- **Isolated Storage Buckets**: Configure separate asset storage contexts cleanly with explicit lifecycle rules. Apply granular security expressions to storage buckets to prevent unauthorized file extraction or resource indexing bugs.

## Code Construction Rules

### 1. Database Migrations & Declarative Policies
- Write distinct, atomic SQL migration files for all schema changes. Ensure every table initialization script includes matching `CREATE POLICY` statements covering `SELECT`, `INSERT`, `UPDATE`, and `DELETE` access pathways.
- When defining multi-tenant workspace rows, cross-reference authenticated session metrics utilizing native security contexts cleanly (`auth.uid()` or validated token claim keys).

### 2. Database Functions & Automation Triggers
- Offload secure system processes (such as automated profile generation during user signup events) to explicit `SECURITY DEFINER` database functions running behind isolated schema boundaries.
- Ensure internal functions validate user structural arguments tightly, capturing systemic drops or transaction rollback faults gracefully inside structured exception paths.

### 3. High-Performance Query Engineering
- Maximize indexing efficiency: queries pulling complex json metrics or relational hierarchies from client libraries must be mapped explicitly to single index keys to prevent costly full table scans.
- Limit real-time dataset streams (`.on()`) to narrow, heavily filtered channels. Avoid opening unfiltered global table mutation feeds that waste client thread lines and infrastructure limits.

### 4. Client Integration & Security Boundaries
- Restrict high-privilege operations entirely to serverless Edge Functions or secure backend environments using the administrative Supabase `service_role` credential token. Never leak service tokens to frontend public repositories or client bundles.
- Ensure client operations map data errors cleanly, hiding internal server error metrics or structural column details from final user response viewports.

## Verification & Testing Workflows
- Validate code robustness by providing integration test setups that simulate unauthenticated or cross-tenant query payloads to verify RLS mechanisms cleanly drop unauthorized actions.

Why this template matters

Supabase accelerates feature delivery by bringing data closer to the client layer, but this structural visibility requires exceptional defense. Left unguided, an AI tool will naturally write loose client calls that omit server validation checks or create tables that accidentally accept raw anonymous writes, leaving your core platform wide open to complete data manipulation or breach paths.

This configuration completely eliminates these application-level vulnerabilities by making PostgreSQL RLS policies mandatory, automating type-safe client initializations, protecting administrative service tokens, and setting up secure database functions natively.

Recommended additions

  • Include explicit workflow instructions for configuring automated TypeScript schema generation scripts using the native Supabase CLI tools during local builds.
  • Add targeted guidance for designing optimized multi-tenant user membership functions that query relational profile rows inside security filters.
  • Define standardized lifecycle policies for managing large file object removals directly from cloud storage buckets.
  • Incorporate specific instruction blocks detailing the deployment and secure authentication of Supabase Edge Functions.

FAQ

Why does this blueprint prioritize PostgreSQL RLS over backend app logic?

Because clients can communicate directly with Supabase via public network lines, application-layer code blocks can be bypassed entirely. Enforcing Row-Level Security (RLS) straight at the core PostgreSQL layer ensures that data boundaries remain completely bulletproof, regardless of whether a query drops from a frontend component, a cloud worker, or an external script.

How are untyped data payload bugs prevented using this setup?

The rules require that all Supabase database client instances explicitly accept the generated type definitions. This forces your AI assistant to flag parameter mismatches or missing properties instantly during typing tasks, maintaining complete code consistency.

When should I use the `service_role` key versus the `anon` key?

The `anon` key respects all user-facing RLS policies and is completely safe for public web applications. The `service_role` key acts as a super-admin token that bypasses all security layers completely. The template strictly mandates restricting the `service_role` key to secure server boundaries, protecting your application from severe infrastructure exploits.

How does this template handle automated actions like user onboarding?

It instructs the AI assistant to build automated event steps by linking isolated database triggers directly to native internal processes (such as tracking user identity signs inside the `auth.users` ecosystem) via highly protected `SECURITY DEFINER` system functions.

About the author

Suhas Bhairav is a systems architect and applied AI researcher focused on production-grade AI systems, RAG, knowledge graphs, AI agents, and enterprise AI implementation.