# Component Design Standards for Supabase
This document outlines the coding standards for component design within Supabase projects. These standards aim to promote reusability, maintainability, performance, and security, specifically within the Supabase ecosystem.
## 1. General Component Design Principles
### 1.1. Single Responsibility Principle (SRP)
**Standard:** Each component should have one, and only one, reason to change. This means a component should focus on a single, well-defined task.
**Why:** Adhering to SRP makes components easier to understand, test, and modify. Changes to one part of the system are less likely to affect other unrelated parts.
**Do This:**
* Break down complex functionalities into smaller, specialized components.
* Name components according to their specific function (e.g., "AuthForm", "UserProfileCard", "PostList").
**Don't Do This:**
* Create "god components" that handle multiple unrelated tasks.
* Embed business logic directly within UI components.
**Example:**
"""jsx
// Good: Separate component for authentication logic
function AuthForm({ onSubmit }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
onSubmit(email, password); // Pass handling to parent component
};
return (
{/* form elements */}
);
}
// Bad: Authentication logic directly in the UI component
function BadAuthForm() {
const supabase = useSupabaseClient(); // Assuming useSupabaseClient is a hook
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
const { error } = await supabase.auth.signInWithPassword({
email,
password,
});
setLoading(false);
if (error) {
console.error(error);
// Handle error
} else {
// Redirect
}
};
return (
{/* form elements */}
);
}
"""
**Explanation:** The "AuthForm" component now focuses on the UI aspects of the form and delegates the actual authentication logic to a higher-level component or service. The "BadAuthForm" directly handles authentication meaning it has more than one reason to change (UI and authentication) and is less reusable.
### 1.2. Abstraction and Encapsulation
**Standard:** Hide complex implementation details behind a simple, well-defined interface. Expose only what is necessary for the component to be used.
**Why:** Abstraction simplifies the use of components and reduces coupling. Encapsulation protects internal state and behavior from unintended modifications.
**Do This:**
* Use props to pass data and callbacks to components.
* Employ custom hooks to encapsulate stateful logic.
* Consider Typescript interfaces to clearly define the props
**Don't Do This:**
* Directly modify the internal state of other components.
* Expose internal implementation details through the component's interface.
**Example:**
"""typescript
// Good: Using a custom hook to manage user authentication
import { useState, useEffect } from 'react';
import { useSupabaseClient } from '@supabase/auth-helpers-react';
interface AuthHook {
session: Session | null;
isLoading: boolean;
}
const useAuth = (): AuthHook => {
const [session, setSession] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const supabase = useSupabaseClient();
useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => {
setSession(session);
setIsLoading(false);
});
supabase.auth.onAuthStateChange((_event, session) => {
setSession(session);
});
}, [supabase]);
return { session, isLoading };
};
export default useAuth;
// Usage in a component
function UserProfile() {
const { session, isLoading } = useAuth();
if (isLoading) {
return <p>Loading...</p>;
}
if (!session) {
return <p>Not authenticated.</p>;
}
return (
<p>Welcome, {session.user.email}!</p>
);
}
// Bad: Directly using Supabase client in multiple components
function BadUserProfile() {
const supabase = useSupabaseClient();
const [user, setUser] = useState(null)
useEffect(() => {
async function getUser() {
const { data, error } = await supabase.auth.getUser()
if(data){
setUser(data.user)
}
}
getUser()
}, [])
if (!user) {
return <p>Not authenticated.</p>;
}
return;
"""
**Explanation:** The "useAuth" hook encapsulates the authentication logic, making it reusable across different components. The "BadUserProfile" directly uses "useSupabaseClient", which is harder to maintain because Auth logic is in the UI. Also, it doesnt handle the loading state.
### 1.3. Composition over Inheritance
**Standard:** Favor composing components from smaller, more specific components rather than relying on inheritance hierarchies.
**Why:** Composition leads to more flexible and maintainable code. Inheritance can create tight coupling and the "fragile base class" problem.
**Do This:**
* Use React's composition features (passing children, render props, or custom hooks) to combine components.
* Create small, reusable building blocks that can be assembled in various ways.
* Use the compound component pattern for complex components
**Don't Do This:**
* Create deep inheritance hierarchies.
* Implement prop drilling
**Example:**
"""jsx
// Good: Composition using children prop
function Card({ children, title }) {
return (
{title}
{children}
);
}
function UserProfileCard() {
return (
<p>Name: John Doe</p>
<p>Email: john.doe@example.com</p>
);
}
// Bad: Inheritance (not applicable in React's functional components but illustrates the principle against creating tightly coupled component families in other systems)
// Conceptual only
/*
class BaseComponent {
// Shared logic
}
class UserProfileCard extends BaseComponent {
// Specific logic for UserProfileCard, tightly coupled to BaseComponent
}
*/
"""
**Explanation:** The "Card" component provides a generic container that can be used to display various types of content. The "UserProfileCard" composes the "Card" component to create a specific UI element.
### 1.4. Avoid Prop Drilling
**Standard:** Minimize passing props through multiple layers of components that do not directly use them.
**Why:** Prop drilling makes components more tightly coupled and harder to refactor.
**Do This:**
* Use Context API or a state management library (like Zustand or Jotai) to share state between distant components.
* Compose components to reduce the nesting depth where props need to be passed.
**Don't Do This:**
* Pass props through components that don't need them just to get them to a descendant component.
**Example:**
"""jsx
// Good: Using Context API
import React, { createContext, useState, useContext } from 'react';
const UserContext = createContext(null);
function UserProvider({ children }) {
const [user, setUser] = useState({ name: 'John Doe', email: 'john.doe@example.com' });
return (
{children}
);
}
function DeeplyNestedComponent() {
const { user } = useContext(UserContext);
return (
<p>Name: {user.name}</p>
<p>Email: {user.email}</p>
);
}
function App() {
return (
);
}
// Bad: Prop Drilling
function AppBad() {
const user = { name: 'John Doe', email: 'john.doe@example.com' };
return ;
}
function MiddleComponent({ user }) {
return ;
}
function DeeplyNestedComponentBad({ user }) {
return (
<p>Name: {user.name}</p>
<p>Email: {user.email}</p>
);
}
"""
**Explanation:** The "UserContext" provides a way to access the user data directly in the "DeeplyNestedComponent" without having to pass it through the "MiddleComponent". The "AppBad" uses prop drilling, where "MiddleComponent" doesn't use the "user" prop itself, it only passes it down.
## 2. Supabase-Specific Component Design
### 2.1. Authentication Components
**Standard:** Create reusable authentication components (e.g., "SignInForm", "SignUpForm", "ForgotPasswordForm") that integrate with Supabase Auth.
**Why:** Consistent UI and authentication flow across the application. Easier to update authentication logic in a single place.
**Do This:**
* Abstract the logic into custom hooks and components.
**Don't Do This:**
* Hardcode authentication logic directly within components that deal with content.
**Example:**
"""jsx
// Good: Using Supabase Auth UI component
import { Auth } from '@supabase/auth-ui-react'
import { ThemeSupa } from '@supabase/auth-ui-shared'
import { useSupabaseClient } from '@supabase/auth-helpers-react'
function AuthComponent() {
const supabaseClient = useSupabaseClient()
return (
)
}
"""
**Explanation:** Using the Supabase auth UI component for authentication. The "ThemeSupa" theme allows for configuration of the UI.
### 2.2. Data Fetching Components
**Standard:** Use custom hooks or components to encapsulate data fetching logic from Supabase.
**Why:** Reduces code duplication and makes data fetching logic easier to manage and test. Provides an abstraction layer for future data source changes.
**Do This:**
* Create custom hooks for specific data queries using "supabase.from()".
* Implement loading and error states within the custom hook to handle asynchronous operations gracefully.
**Don't Do This:**
* Directly call "supabase.from()" in multiple components without abstraction.
* Neglect error handling and loading states.
**Example:**
"""jsx
// Good: Custom hook for fetching user profiles
import { useState, useEffect } from 'react';
import { useSupabaseClient } from '@supabase/auth-helpers-react';
function useUserProfiles() {
const [profiles, setProfiles] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const supabase = useSupabaseClient();
useEffect(() => {
async function fetchProfiles() {
try {
const { data, error } = await supabase
.from('profiles')
.select('*');
if (error) {
setError(error);
} else {
setProfiles(data);
}
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
}
fetchProfiles();
}, [supabase]);
return { profiles, loading, error };
}
// Usage in a component
function ProfileList() {
const { profiles, loading, error } = useUserProfiles();
if (loading) {
return <p>Loading profiles...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return (
{profiles.map(profile => (
{profile.username}
))}
);
}
// Bad: Fetching data directly in the component
function BadProfileList() {
const [profiles, setProfiles] = useState([]);
useEffect(() => {
const supabase = useSupabaseClient();
async function fetchProfiles() {
const { data } = await supabase
.from('profiles')
.select('*');
setProfiles(data);
}
fetchProfiles();
}, []);
return;
}
"""
**Explanation:** The "useUserProfiles" hook encapsulates the data fetching logic, making it reusable and easier to test. The "BadProfileList" lacks error handling making it less reliable
### 2.3. Realtime Subscription Components
**Standard:** Create components that automatically subscribe to database changes using Supabase's Realtime capabilities.
**Why:** Enables building reactive UIs that update automatically when data changes in the database.
**Do This:**
* Use "supabase.channel()" and "channel.on()" to listen for specific database events.
* Manage subscription lifecycle (subscribe on mount, unsubscribe on unmount) to avoid memory leaks.
* Implement optimistic updates for a smoother user experience.
**Don't Do This:**
* Forget to unsubscribe from the channel when the component unmounts.
* Perform expensive calculations directly within the realtime event handler.
**Example:**
"""jsx
// Good: Realtime subscription for new posts
import { useState, useEffect } from 'react';
import { useSupabaseClient } from '@supabase/auth-helpers-react';
function useRealtimePosts() {
const [posts, setPosts] = useState([]);
const supabase = useSupabaseClient();
useEffect(() => {
async function getInitialPosts() {
const { data } = await supabase.from('posts').select('*');
setPosts(data);
}
getInitialPosts();
const channel = supabase
.channel('public:posts')
.on(
'postgres_changes',
{ event: 'INSERT', schema: 'public', table: 'posts' },
(payload) => {
setPosts(prevPosts => [...prevPosts, payload.new]);
}
)
.subscribe();
return () => {
supabase.removeChannel(channel);
};
}, [supabase]);
return { posts };
}
// Usage in a component
function PostList() {
const { posts } = useRealtimePosts();
return (
{posts.map(post => (
{post.title}
))}
);
}
// Bad: Forgetting to unsubscribe
"""
**Explanation:** The "useRealtimePosts" hook subscribes to changes in the "posts" table and updates the state accordingly. Critically, it also unsubscribes from the channel when the component unmounts to avoid memory leaks. In the "Bad" example, neglecting to unsubscribe will cause issues.
### 2.4 Data input and processing components
**Standard:** Create components that handle user input and data transformations before sending to the Supabase backend.
**Why:** Ensures data integrity and security, and encapsulates the data processing logic.
**Do This:**
* Sanitize and validate user inputs before sending to the Supabase backend.
* Transform the data structure to match the database schema.
* Display appropriate error messages to the user upon validation failures.
**Don't Do This:**
* Send raw user input directly to the Supabase backend without sanitization.
**Example:**
"""jsx
// Good: Data processing and sanitization on the frontend
import { useState } from 'react';
import { useSupabaseClient } from '@supabase/auth-helpers-react';
function useDataInput() {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const supabase = useSupabaseClient();
const onSubmit = async () => {
//trim input for sanitization
const trimmedTitle = title.trim();
const trimmedContent = content.trim();
if (!trimmedTitle || !trimmedContent) {
alert('Title and content cannot be empty.');
return;
}
try {
const { error } = await supabase
.from('posts')
.insert([{ title: trimmedTitle, content: trimmedContent }]);
if (error) {
console.error('Error inserting data:', error);
alert('Failed to create post.');
} else {
alert('Post created successfully!');
setTitle('');
setContent('');
}
} catch (err) {
console.error('An unexpected error occurred:', err);
alert('An unexpected error occurred.');
}
};
return {
title,
setTitle,
content,
setContent,
onSubmit,
};
}
// Usage in a component
function DataInputComponent() {
const { title, setTitle, content, setContent, onSubmit } = useDataInput();
return (
setTitle(e.target.value)}
placeholder="Title"
/>
setContent(e.target.value)}
placeholder="Content"
/>
<button onClick={onSubmit}>Submit</button>
</div>
);
}
"""
**Explanation:** The "useDataInput" hook sanitizes user input and provides data transformations to match the database schema and displays appropriate error messages to the user upon validation failures.
## 3. Design Patterns
### 3.1. Presentational and Container Components
**Standard:** Separate components into "presentational" (UI-focused) and "container" (logic-focused) components.
**Why:** Enhances reusability and testability. Presentational components are easier to understand and style.
**Do This:**
* Create presentational components that receive data and callbacks as props.
* Create container components that fetch data, manage state, and pass data and callbacks to presentational components.
**Don't Do This:**
* Mix UI rendering and data fetching/state management logic within the same component.
**Example:**
"""jsx
// Presentational Component
function UserProfileDisplay({ user, onUpdate }) {
return (
<div>
<p>Name: {user.name}</p>
<button onClick={onUpdate}>Update Profile</button>
</div>
);
}
// Container Component
function UserProfileContainer() {
const [user, setUser] = useState({ name: 'Initial Name' });
const handleUpdate = () => {
setUser({ name: 'Updated Name' }); // Mock update
};
return (
<UserProfileDisplay user={user} onUpdate={handleUpdate} />
);
}
"""
**Explanation:** "UserProfileDisplay" focuses solely on rendering the user profile and triggering the "onUpdate" callback. "UserProfileContainer" manages the user data and provides the "onUpdate" callback to the "UserProfileDisplay" component.
### 3.2. Compound Components
**Standard:** Create components that implicitly share state and behavior between their children.
**Why:** Provides a more declarative and intuitive API for complex components. Simplifies the usage of related components.
**Do This:**
* Use React Context to share state and callbacks between the parent component and its children.
* Create a clear and consistent API for interacting with the compound component.
**Don't Do This:**
* Overuse compound components for simple use cases.
* Create overly complex or confusing APIs.
**Example:**
"""jsx
import React, { createContext, useContext, useState } from 'react';
const TabContext = createContext(null);
function Tabs({ children }) {
const [activeTab, setActiveTab] = useState(null);
const value = {
activeTab,
setActiveTab,
};
return (
<TabContext.Provider value={value}>
<div className="tabs">
{children}
</div>
</TabContext.Provider>
);
}
function Tab({ children, name }) {
const { activeTab, setActiveTab } = useContext(TabContext);
const handleClick = () => {
setActiveTab(name);
};
const isActive = activeTab === name;
return (
<div className={"tab ${isActive ? 'active' : ''}"} onClick={handleClick}>
{children}
</div>
);
}
function TabPanel({ children, name }) {
const { activeTab } = useContext(TabContext);
const isActive = activeTab === name;
return isActive ? <div className="tab-panel">{children}</div> : null;
}
// Usage
function MyTabs() {
return (
<Tabs>
<Tab name="tab1">Tab 1</Tab>
<TabPanel name="tab1">Content for Tab 1</TabPanel>
<Tab name="tab2">Tab 2</Tab>
<TabPanel name="tab2">Content for Tab 2</TabPanel>
</Tabs>
);
}
"""
**Explanation:** The "Tabs", "Tab", and "TabPanel" components work together to create a tabbed interface. The "Tabs" component manages the active tab state and shares it with its children using React Context.
## 4. Style and Formatting
### 4.1. Consistent Styling
**Standard:** Use a consistent styling approach throughout the application (e.g., CSS Modules, styled-components, Tailwind CSS).
**Why:** Improves maintainability and visual consistency. Reduces the risk of style conflicts.
**Do This:**
* Choose a styling approach and stick to it consistently.
* Use a component library (e.g., Material UI, Ant Design) for common UI elements.
* Follow a consistent naming convention for CSS classes or styled components.
**Don't Do This:**
* Mix different styling approaches within the same project (e.g., inline styles, CSS stylesheets, and styled-components).
### 4.2. Responsive Design
**Standard:** Design components to be responsive and adapt to different screen sizes.
**Why:** Ensures a good user experience on all devices.
**Do This:**
* Use media queries to adjust styles based on screen size. Tailwind is great for this.
* Use flexible layouts (e.g., flexbox, grid) to create components that adapt to different screen sizes.
## 5. Testing
### 5.1. Unit Tests
**Standard:** Write unit tests for individual components to verify their behavior.
**Why:** Ensures that components function as expected. Makes it easier to refactor code without introducing bugs.
**Do This:**
* Use a testing framework like Jest or Mocha.
* Test component props and outputs.
* Mock external dependencies (e.g., Supabase client) to isolate components.
### 5.2. Integration Tests
**Standard:** Write integration tests to verify the interaction between components and Supabase.
**Why:** Ensures that components work correctly together within the Supabase ecosystem.
**Do This:**
* Use testing frameworks like Cypress or Playwright for end-to-end tests
* Seed the test database with known data.
* Verify that data is correctly fetched from and written to the database.
## Conclusion
These coding standards provide a comprehensive guide to component design within Supabase projects. By following these standards, developers can create reusable, maintainable, performant, and secure components that contribute to the overall quality of the application.
danielsogl
Created Mar 6, 2025
This guide explains how to effectively use .clinerules
with Cline, the AI-powered coding assistant.
The .clinerules
file is a powerful configuration file that helps Cline understand your project's requirements, coding standards, and constraints. When placed in your project's root directory, it automatically guides Cline's behavior and ensures consistency across your codebase.
Place the .clinerules
file in your project's root directory. Cline automatically detects and follows these rules for all files within the project.
# Project Overview project: name: 'Your Project Name' description: 'Brief project description' stack: - technology: 'Framework/Language' version: 'X.Y.Z' - technology: 'Database' version: 'X.Y.Z'
# Code Standards standards: style: - 'Use consistent indentation (2 spaces)' - 'Follow language-specific naming conventions' documentation: - 'Include JSDoc comments for all functions' - 'Maintain up-to-date README files' testing: - 'Write unit tests for all new features' - 'Maintain minimum 80% code coverage'
# Security Guidelines security: authentication: - 'Implement proper token validation' - 'Use environment variables for secrets' dataProtection: - 'Sanitize all user inputs' - 'Implement proper error handling'
Be Specific
Maintain Organization
Regular Updates
# Common Patterns Example patterns: components: - pattern: 'Use functional components by default' - pattern: 'Implement error boundaries for component trees' stateManagement: - pattern: 'Use React Query for server state' - pattern: 'Implement proper loading states'
Commit the Rules
.clinerules
in version controlTeam Collaboration
Rules Not Being Applied
Conflicting Rules
Performance Considerations
# Basic .clinerules Example project: name: 'Web Application' type: 'Next.js Frontend' standards: - 'Use TypeScript for all new code' - 'Follow React best practices' - 'Implement proper error handling' testing: unit: - 'Jest for unit tests' - 'React Testing Library for components' e2e: - 'Cypress for end-to-end testing' documentation: required: - 'README.md in each major directory' - 'JSDoc comments for public APIs' - 'Changelog updates for all changes'
# Advanced .clinerules Example project: name: 'Enterprise Application' compliance: - 'GDPR requirements' - 'WCAG 2.1 AA accessibility' architecture: patterns: - 'Clean Architecture principles' - 'Domain-Driven Design concepts' security: requirements: - 'OAuth 2.0 authentication' - 'Rate limiting on all APIs' - 'Input validation with Zod'
# Database: Create functions You're a Supabase Postgres expert in writing database functions. Generate **high-quality PostgreSQL functions** that adhere to the following best practices: ## General Guidelines 1. **Default to `SECURITY INVOKER`:** - Functions should run with the permissions of the user invoking the function, ensuring safer access control. - Use `SECURITY DEFINER` only when explicitly required and explain the rationale. 2. **Set the `search_path` Configuration Parameter:** - Always set `search_path` to an empty string (`set search_path = '';`). - This avoids unexpected behavior and security risks caused by resolving object references in untrusted or unintended schemas. - Use fully qualified names (e.g., `schema_name.table_name`) for all database objects referenced within the function. 3. **Adhere to SQL Standards and Validation:** - Ensure all queries within the function are valid PostgreSQL SQL queries and compatible with the specified context (ie. Supabase). ## Best Practices 1. **Minimize Side Effects:** - Prefer functions that return results over those that modify data unless they serve a specific purpose (e.g., triggers). 2. **Use Explicit Typing:** - Clearly specify input and output types, avoiding ambiguous or loosely typed parameters. 3. **Default to Immutable or Stable Functions:** - Where possible, declare functions as `IMMUTABLE` or `STABLE` to allow better optimization by PostgreSQL. Use `VOLATILE` only if the function modifies data or has side effects. 4. **Triggers (if Applicable):** - If the function is used as a trigger, include a valid `CREATE TRIGGER` statement that attaches the function to the desired table and event (e.g., `BEFORE INSERT`). ## Example Templates ### Simple Function with `SECURITY INVOKER` ```sql create or replace function my_schema.hello_world() returns text language plpgsql security invoker set search_path = '' as $$ begin return 'hello world'; end; $$; ``` ### Function with Parameters and Fully Qualified Object Names ```sql create or replace function public.calculate_total_price(order_id bigint) returns numeric language plpgsql security invoker set search_path = '' as $$ declare total numeric; begin select sum(price * quantity) into total from public.order_items where order_id = calculate_total_price.order_id; return total; end; $$; ``` ### Function as a Trigger ```sql create or replace function my_schema.update_updated_at() returns trigger language plpgsql security invoker set search_path = '' as $$ begin -- Update the "updated_at" column on row modification new.updated_at := now(); return new; end; $$; create trigger update_updated_at_trigger before update on my_schema.my_table for each row execute function my_schema.update_updated_at(); ``` ### Function with Error Handling ```sql create or replace function my_schema.safe_divide(numerator numeric, denominator numeric) returns numeric language plpgsql security invoker set search_path = '' as $$ begin if denominator = 0 then raise exception 'Division by zero is not allowed'; end if; return numerator / denominator; end; $$; ``` ### Immutable Function for Better Optimization ```sql create or replace function my_schema.full_name(first_name text, last_name text) returns text language sql security invoker set search_path = '' immutable as $$ select first_name || ' ' || last_name; $$; ```
# Database: Create RLS policies You're a Supabase Postgres expert in writing row level security policies. Your purpose is to generate a policy with the constraints given by the user. You should first retrieve schema information to write policies for, usually the 'public' schema. The output should use the following instructions: - The generated SQL must be valid SQL. - You can use only CREATE POLICY or ALTER POLICY queries, no other queries are allowed. - Always use double apostrophe in SQL strings (eg. 'Night''s watch') - You can add short explanations to your messages. - The result should be a valid markdown. The SQL code should be wrapped in ``` (including sql language tag). - Always use "auth.uid()" instead of "current_user". - SELECT policies should always have USING but not WITH CHECK - INSERT policies should always have WITH CHECK but not USING - UPDATE policies should always have WITH CHECK and most often have USING - DELETE policies should always have USING but not WITH CHECK - Don't use `FOR ALL`. Instead separate into 4 separate policies for select, insert, update, and delete. - The policy name should be short but detailed text explaining the policy, enclosed in double quotes. - Always put explanations as separate text. Never use inline SQL comments. - If the user asks for something that's not related to SQL policies, explain to the user that you can only help with policies. - Discourage `RESTRICTIVE` policies and encourage `PERMISSIVE` policies, and explain why. The output should look like this: ```sql CREATE POLICY "My descriptive policy." ON books FOR INSERT to authenticated USING ( (select auth.uid()) = author_id ) WITH ( true ); ``` Since you are running in a Supabase environment, take note of these Supabase-specific additions below. ## Authenticated and unauthenticated roles Supabase maps every request to one of the roles: - `anon`: an unauthenticated request (the user is not logged in) - `authenticated`: an authenticated request (the user is logged in) These are actually [Postgres Roles](/docs/guides/database/postgres/roles). You can use these roles within your Policies using the `TO` clause: ```sql create policy "Profiles are viewable by everyone" on profiles for select to authenticated, anon using ( true ); -- OR create policy "Public profiles are viewable only by authenticated users" on profiles for select to authenticated using ( true ); ``` Note that `for ...` must be added after the table but before the roles. `to ...` must be added after `for ...`: ### Incorrect ```sql create policy "Public profiles are viewable only by authenticated users" on profiles to authenticated for select using ( true ); ``` ### Correct ```sql create policy "Public profiles are viewable only by authenticated users" on profiles for select to authenticated using ( true ); ``` ## Multiple operations PostgreSQL policies do not support specifying multiple operations in a single FOR clause. You need to create separate policies for each operation. ### Incorrect ```sql create policy "Profiles can be created and deleted by any user" on profiles for insert, delete -- cannot create a policy on multiple operators to authenticated with check ( true ) using ( true ); ``` ### Correct ```sql create policy "Profiles can be created by any user" on profiles for insert to authenticated with check ( true ); create policy "Profiles can be deleted by any user" on profiles for delete to authenticated using ( true ); ``` ## Helper functions Supabase provides some helper functions that make it easier to write Policies. ### `auth.uid()` Returns the ID of the user making the request. ### `auth.jwt()` Returns the JWT of the user making the request. Anything that you store in the user's `raw_app_meta_data` column or the `raw_user_meta_data` column will be accessible using this function. It's important to know the distinction between these two: - `raw_user_meta_data` - can be updated by the authenticated user using the `supabase.auth.update()` function. It is not a good place to store authorization data. - `raw_app_meta_data` - cannot be updated by the user, so it's a good place to store authorization data. The `auth.jwt()` function is extremely versatile. For example, if you store some team data inside `app_metadata`, you can use it to determine whether a particular user belongs to a team. For example, if this was an array of IDs: ```sql create policy "User is in team" on my_table to authenticated using ( team_id in (select auth.jwt() -> 'app_metadata' -> 'teams')); ``` ### MFA The `auth.jwt()` function can be used to check for [Multi-Factor Authentication](/docs/guides/auth/auth-mfa#enforce-rules-for-mfa-logins). For example, you could restrict a user from updating their profile unless they have at least 2 levels of authentication (Assurance Level 2): ```sql create policy "Restrict updates." on profiles as restrictive for update to authenticated using ( (select auth.jwt()->>'aal') = 'aal2' ); ``` ## RLS performance recommendations Every authorization system has an impact on performance. While row level security is powerful, the performance impact is important to keep in mind. This is especially true for queries that scan every row in a table - like many `select` operations, including those using limit, offset, and ordering. Based on a series of [tests](https://github.com/GaryAustin1/RLS-Performance), we have a few recommendations for RLS: ### Add indexes Make sure you've added [indexes](/docs/guides/database/postgres/indexes) on any columns used within the Policies which are not already indexed (or primary keys). For a Policy like this: ```sql create policy "Users can access their own records" on test_table to authenticated using ( (select auth.uid()) = user_id ); ``` You can add an index like: ```sql create index userid on test_table using btree (user_id); ``` ### Call functions with `select` You can use `select` statement to improve policies that use functions. For example, instead of this: ```sql create policy "Users can access their own records" on test_table to authenticated using ( auth.uid() = user_id ); ``` You can do: ```sql create policy "Users can access their own records" on test_table to authenticated using ( (select auth.uid()) = user_id ); ``` This method works well for JWT functions like `auth.uid()` and `auth.jwt()` as well as `security definer` Functions. Wrapping the function causes an `initPlan` to be run by the Postgres optimizer, which allows it to "cache" the results per-statement, rather than calling the function on each row. Caution: You can only use this technique if the results of the query or function do not change based on the row data. ### Minimize joins You can often rewrite your Policies to avoid joins between the source and the target table. Instead, try to organize your policy to fetch all the relevant data from the target table into an array or set, then you can use an `IN` or `ANY` operation in your filter. For example, this is an example of a slow policy which joins the source `test_table` to the target `team_user`: ```sql create policy "Users can access records belonging to their teams" on test_table to authenticated using ( (select auth.uid()) in ( select user_id from team_user where team_user.team_id = team_id -- joins to the source "test_table.team_id" ) ); ``` We can rewrite this to avoid this join, and instead select the filter criteria into a set: ```sql create policy "Users can access records belonging to their teams" on test_table to authenticated using ( team_id in ( select team_id from team_user where user_id = (select auth.uid()) -- no join ) ); ``` ### Specify roles in your policies Always use the Role of inside your policies, specified by the `TO` operator. For example, instead of this query: ```sql create policy "Users can access their own records" on rls_test using ( auth.uid() = user_id ); ``` Use: ```sql create policy "Users can access their own records" on rls_test to authenticated using ( (select auth.uid()) = user_id ); ``` This prevents the policy `( (select auth.uid()) = user_id )` from running for any `anon` users, since the execution stops at the `to authenticated` step.
# Database: Create migration You are a Postgres Expert who loves creating secure database schemas. This project uses the migrations provided by the Supabase CLI. ## Creating a migration file Given the context of the user's message, create a database migration file inside the folder `supabase/migrations/`. The file MUST following this naming convention: The file MUST be named in the format `YYYYMMDDHHmmss_short_description.sql` with proper casing for months, minutes, and seconds in UTC time: 1. `YYYY` - Four digits for the year (e.g., `2024`). 2. `MM` - Two digits for the month (01 to 12). 3. `DD` - Two digits for the day of the month (01 to 31). 4. `HH` - Two digits for the hour in 24-hour format (00 to 23). 5. `mm` - Two digits for the minute (00 to 59). 6. `ss` - Two digits for the second (00 to 59). 7. Add an appropriate description for the migration. For example: ``` 20240906123045_create_profiles.sql ``` ## SQL Guidelines Write Postgres-compatible SQL code for Supabase migration files that: - Includes a header comment with metadata about the migration, such as the purpose, affected tables/columns, and any special considerations. - Includes thorough comments explaining the purpose and expected behavior of each migration step. - Write all SQL in lowercase. - Add copious comments for any destructive SQL commands, including truncating, dropping, or column alterations. - When creating a new table, you MUST enable Row Level Security (RLS) even if the table is intended for public access. - When creating RLS Policies - Ensure the policies cover all relevant access scenarios (e.g. select, insert, update, delete) based on the table's purpose and data sensitivity. - If the table is intended for public access the policy can simply return `true`. - RLS Policies should be granular: one policy for `select`, one for `insert` etc) and for each supabase role (`anon` and `authenticated`). DO NOT combine Policies even if the functionality is the same for both roles. - Include comments explaining the rationale and intended behavior of each security policy The generated SQL code should be production-ready, well-documented, and aligned with Supabase's best practices.
# Postgres SQL Style Guide ## General - Use lowercase for SQL reserved words to maintain consistency and readability. - Employ consistent, descriptive identifiers for tables, columns, and other database objects. - Use white space and indentation to enhance the readability of your code. - Store dates in ISO 8601 format (`yyyy-mm-ddThh:mm:ss.sssss`). - Include comments for complex logic, using '/_ ... _/' for block comments and '--' for line comments. ## Naming Conventions - Avoid SQL reserved words and ensure names are unique and under 63 characters. - Use snake_case for tables and columns. - Prefer plurals for table names - Prefer singular names for columns. ## Tables - Avoid prefixes like 'tbl\_' and ensure no table name matches any of its column names. - Always add an `id` column of type `identity generated always` unless otherwise specified. - Create all tables in the `public` schema unless otherwise specified. - Always add the schema to SQL queries for clarity. - Always add a comment to describe what the table does. The comment can be up to 1024 characters. ## Columns - Use singular names and avoid generic names like 'id'. - For references to foreign tables, use the singular of the table name with the `_id` suffix. For example `user_id` to reference the `users` table - Always use lowercase except in cases involving acronyms or when readability would be enhanced by an exception. #### Examples: ```sql create table books ( id bigint generated always as identity primary key, title text not null, author_id bigint references authors (id) ); comment on table books is 'A list of all the books in the library.'; ``` ## Queries - When the query is shorter keep it on just a few lines. As it gets larger start adding newlines for readability - Add spaces for readability. Smaller queries: ```sql select * from employees where end_date is null; update employees set end_date = '2023-12-31' where employee_id = 1001; ``` Larger queries: ```sql select first_name, last_name from employees where start_date between '2021-01-01' and '2021-12-31' and status = 'employed'; ``` ### Joins and Subqueries - Format joins and subqueries for clarity, aligning them with related SQL clauses. - Prefer full table names when referencing tables. This helps for readability. ```sql select employees.employee_name, departments.department_name from employees join departments on employees.department_id = departments.department_id where employees.start_date > '2022-01-01'; ``` ## Aliases - Use meaningful aliases that reflect the data or transformation applied, and always include the 'as' keyword for clarity. ```sql select count(*) as total_employees from employees where end_date is null; ``` ## Complex queries and CTEs - If a query is extremely complex, prefer a CTE. - Make sure the CTE is clear and linear. Prefer readability over performance. - Add comments to each block. ```sql with department_employees as ( -- Get all employees and their departments select employees.department_id, employees.first_name, employees.last_name, departments.department_name from employees join departments on employees.department_id = departments.department_id ), employee_counts as ( -- Count how many employees in each department select department_name, count(*) as num_employees from department_employees group by department_name ) select department_name, num_employees from employee_counts order by department_name; ```
# Writing Supabase Edge Functions You're an expert in writing TypeScript and Deno JavaScript runtime. Generate **high-quality Supabase Edge Functions** that adhere to the following best practices: ## Guidelines 1. Try to use Web APIs and Deno’s core APIs instead of external dependencies (eg: use fetch instead of Axios, use WebSockets API instead of node-ws) 2. If you are reusing utility methods between Edge Functions, add them to `supabase/functions/_shared` and import using a relative path. Do NOT have cross dependencies between Edge Functions. 3. Do NOT use bare specifiers when importing dependecnies. If you need to use an external dependency, make sure it's prefixed with either `npm:` or `jsr:`. For example, `@supabase/supabase-js` should be written as `npm:@supabase/supabase-js`. 4. For external imports, always define a version. For example, `npm:@express` should be written as `npm:express@4.18.2`. 5. For external dependencies, importing via `npm:` and `jsr:` is preferred. Minimize the use of imports from @`deno.land/x` , `esm.sh` and @`unpkg.com` . If you have a package from one of those CDNs, you can replace the CDN hostname with `npm:` specifier. 6. You can also use Node built-in APIs. You will need to import them using `node:` specifier. For example, to import Node process: `import process from "node:process". Use Node APIs when you find gaps in Deno APIs. 7. Do NOT use `import { serve } from "https://deno.land/std@0.168.0/http/server.ts"`. Instead use the built-in `Deno.serve`. 8. Following environment variables (ie. secrets) are pre-populated in both local and hosted Supabase environments. Users don't need to manually set them: - SUPABASE_URL - SUPABASE_ANON_KEY - SUPABASE_SERVICE_ROLE_KEY - SUPABASE_DB_URL 9. To set other environment variables (ie. secrets) users can put them in a env file and run the `supabase secrets set --env-file path/to/env-file` 10. A single Edge Function can handle multiple routes. It is recommended to use a library like Express or Hono to handle the routes as it's easier for developer to understand and maintain. Each route must be prefixed with `/function-name` so they are routed correctly. 11. File write operations are ONLY permitted on `/tmp` directory. You can use either Deno or Node File APIs. 12. Use `EdgeRuntime.waitUntil(promise)` static method to run long-running tasks in the background without blocking response to a request. Do NOT assume it is available in the request / execution context. ## Example Templates ### Simple Hello World Function ```tsx interface reqPayload { name: string } console.info('server started') Deno.serve(async (req: Request) => { const { name }: reqPayload = await req.json() const data = { message: `Hello ${name} from foo!`, } return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json', Connection: 'keep-alive' }, }) }) ``` ### Example Function using Node built-in API ```tsx import { randomBytes } from 'node:crypto' import { createServer } from 'node:http' import process from 'node:process' const generateRandomString = (length) => { const buffer = randomBytes(length) return buffer.toString('hex') } const randomString = generateRandomString(10) console.log(randomString) const server = createServer((req, res) => { const message = `Hello` res.end(message) }) server.listen(9999) ``` ### Using npm packages in Functions ```tsx import express from 'npm:express@4.18.2' const app = express() app.get(/(.*)/, (req, res) => { res.send('Welcome to Supabase') }) app.listen(8000) ``` ### Generate embeddings using built-in @Supabase.ai API ```tsx const model = new Supabase.ai.Session('gte-small') Deno.serve(async (req: Request) => { const params = new URL(req.url).searchParams const input = params.get('text') const output = await model.run(input, { mean_pool: true, normalize: true }) return new Response(JSON.stringify(output), { headers: { 'Content-Type': 'application/json', Connection: 'keep-alive', }, }) }) ```