Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+347 -281
View File
@@ -1,283 +1,349 @@
---
description: Comprehensive best practices for developing with Supabase, covering code organization, performance, security, testing, and common pitfalls. This rule provides actionable guidance for developers to build robust and scalable applications using Supabase.
globs: *.js,*.jsx,*.ts,*.tsx,*.sql
description: Comprehensive guidelines for writing high-performance, secure, and maintainable Supabase applications, covering SQL style, data modeling, security, and testing.
globs: **/*
---
# Supabase Best Practices: A Comprehensive Guide
This document outlines best practices for developing with Supabase, covering various aspects from code organization to security and performance.
## 1. Code Organization and Structure
A well-organized codebase is crucial for maintainability and scalability. Here's how to structure your Supabase project:
### 1.1. Directory Structure Best Practices
Adopt a modular structure that separates concerns:
project-root/
├── src/
│ ├── components/ # Reusable UI components
│ ├── pages/ # Page-level components (routes)
│ ├── services/ # Supabase client initialization and data fetching
│ │ ├── supabase.ts # Supabase client initialization
│ │ ├── auth.ts # Authentication-related functions
│ │ ├── database.ts # Database interaction functions
│ ├── utils/ # Utility functions (e.g., date formatting)
│ ├── types/ # TypeScript types and interfaces
│ ├── hooks/ # Custom React hooks
│ ├── styles/ # Global styles and theme
│ └── App.tsx # Main application component
├── migrations/ # Database migrations
├── tests/ # Unit and integration tests
├── .env # Environment variables
└── package.json # Project dependencies
### 1.2. File Naming Conventions
* **Components:** Use PascalCase (e.g., `UserProfile.tsx`).
* **Functions:** Use camelCase (e.g., `fetchUserData`).
* **Variables:** Use camelCase (e.g., `userName`).
* **Files:** Use kebab-case (e.g., `user-profile.tsx`).
### 1.3. Module Organization
* Group related functionalities into modules.
* Use clear and descriptive module names.
* Export only what is necessary from each module to minimize the API surface.
### 1.4. Component Architecture
* Favor small, reusable components.
* Use a component-based approach (e.g., React, Vue.js) to build UIs.
* Separate presentational components from container components to improve reusability and testability.
### 1.5. Code Splitting Strategies
* Use dynamic imports to lazy-load modules.
* Split large components into smaller chunks.
* Implement route-based code splitting to load only the necessary code for each route.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns Specific to Supabase
* **Repository Pattern:** Abstract database interactions behind a repository interface for better testability and maintainability.
* **Observer Pattern:** Utilize Supabase's real-time capabilities to implement reactive UIs.
### 2.2. Recommended Approaches for Common Tasks
* **Data Fetching:** Create reusable functions for fetching data from Supabase tables.
* **Authentication:** Use Supabase Auth for user authentication and authorization.
* **Real-time Updates:** Leverage Supabase Realtime for real-time data synchronization.
* **File Storage:** Utilize Supabase Storage for managing file uploads and downloads.
### 2.3. Anti-patterns and Code Smells to Avoid
* **Direct Database Access from UI Components:** This tightly couples the UI to the database and makes testing difficult. Use a service layer to abstract database interactions.
* **Overusing Supabase Functions and Policies:** Keep business logic in your application code whenever possible to avoid vendor lock-in and improve testability.
* **Manually Creating Tables Without an ORM:** Always use an ORM to manage your database schema and migrations.
* **Ignoring Error Handling:** Implement proper error handling to prevent unexpected crashes and provide informative error messages to users.
* **Storing Sensitive Data in Plain Text:** Never store sensitive data like passwords or API keys in plain text. Use encryption and secure storage mechanisms.
### 2.4. State Management Best Practices
* Choose a state management library (e.g., Redux, Zustand, Recoil) based on your project's complexity.
* Use local component state for simple UI state.
* Centralize application state in a global store for complex data dependencies.
* Use asynchronous actions to handle data fetching and updates.
### 2.5. Error Handling Patterns
* Use try-catch blocks to handle exceptions.
* Implement a global error handler to catch unhandled exceptions.
* Log errors to a monitoring service for tracking and analysis.
* Display user-friendly error messages to the user.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Indexing:** Add indexes to frequently queried columns to improve query performance.
* **Query Optimization:** Use efficient SQL queries and avoid N+1 query problems.
* **Caching:** Implement caching strategies to reduce database load.
* **Connection Pooling:** Use connection pooling to reuse database connections and reduce overhead.
### 3.2. Memory Management
* Avoid memory leaks by properly cleaning up resources.
* Use garbage collection to reclaim unused memory.
* Optimize data structures to reduce memory usage.
### 3.3. Rendering Optimization
* Use memoization techniques to prevent unnecessary re-renders.
* Virtualize long lists to improve rendering performance.
* Optimize images and other assets to reduce file sizes.
### 3.4. Bundle Size Optimization
* Use tree shaking to remove unused code.
* Minify code to reduce file sizes.
* Compress assets to reduce transfer times.
### 3.5. Lazy Loading Strategies
* Lazy load images and other assets that are not immediately visible.
* Implement infinite scrolling to load data in chunks as the user scrolls.
* Use code splitting to load only the necessary code for each route.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and How to Prevent Them
* **SQL Injection:** Prevent SQL injection by using parameterized queries and prepared statements.
* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection to prevent unauthorized requests.
* **Authentication and Authorization Issues:** Secure your authentication and authorization mechanisms to prevent unauthorized access.
### 4.2. Input Validation
* Validate all user input to prevent malicious data from entering your system.
* Use server-side validation in addition to client-side validation.
* Sanitize user input to remove potentially harmful characters.
### 4.3. Authentication and Authorization Patterns
* Use Supabase Auth for user authentication and authorization.
* Implement role-based access control (RBAC) to manage user permissions.
* Use row-level security (RLS) to control data access at the row level.
### 4.4. Data Protection Strategies
* Encrypt sensitive data at rest and in transit.
* Use secure storage mechanisms to store API keys and other secrets.
* Implement data masking to protect sensitive data from unauthorized access.
### 4.5. Secure API Communication
* Use HTTPS to encrypt API traffic.
* Implement API rate limiting to prevent abuse.
* Validate API requests to prevent malicious input.
## 5. Testing Approaches
### 5.1. Unit Testing Strategies
* Write unit tests for individual functions and components.
* Use mocking and stubbing to isolate units of code.
* Aim for high code coverage.
### 5.2. Integration Testing
* Write integration tests to verify the interaction between different parts of your system.
* Test the integration between your application and Supabase.
### 5.3. End-to-end Testing
* Write end-to-end tests to simulate user interactions and verify the overall functionality of your application.
* Use tools like Cypress or Playwright to automate end-to-end tests.
### 5.4. Test Organization
* Organize tests into separate directories based on functionality.
* Use descriptive test names.
* Keep tests concise and focused.
### 5.5. Mocking and Stubbing
* Use mocking to replace external dependencies with controlled substitutes.
* Use stubbing to replace specific method calls with predefined values.
* Avoid over-mocking, as it can make tests less reliable.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes Developers Make
* Not using an ORM for database schema management.
* Over-relying on Supabase functions and policies for business logic.
* Using Supabase-only features without considering open-source alternatives.
* Ignoring error handling and security best practices.
### 6.2. Edge Cases to Be Aware Of
* Handling large datasets efficiently.
* Dealing with real-time data synchronization conflicts.
* Managing user sessions and authentication tokens securely.
### 6.3. Version-Specific Issues
* Be aware of breaking changes in Supabase and its dependencies.
* Test your application thoroughly after upgrading Supabase or its dependencies.
* Refer to the Supabase documentation for migration guides.
### 6.4. Compatibility Concerns
* Ensure compatibility between your application and the Supabase client library.
* Test your application on different browsers and devices.
### 6.5. Debugging Strategies
* Use browser developer tools to debug client-side code.
* Use server-side logging to track errors and performance issues.
* Use the Supabase dashboard to monitor database activity.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* Supabase CLI: For local development and database management.
* VS Code: For code editing and debugging.
* Drizzle ORM: For database schema management.
* Postman/Insomnia: For testing API endpoints.
### 7.2. Build Configuration
* Use a build tool like Webpack or Parcel to bundle your code.
* Configure your build tool to optimize for production.
* Use environment variables to configure your application.
### 7.3. Linting and Formatting
* Use ESLint to enforce code style and prevent errors.
* Use Prettier to format your code automatically.
* Integrate linting and formatting into your development workflow.
### 7.4. Deployment Best Practices
* Use a CI/CD pipeline to automate deployments.
* Deploy your application to a production-ready environment.
* Monitor your application for errors and performance issues.
### 7.5. CI/CD Integration
* Use a CI/CD tool like GitHub Actions or GitLab CI to automate your build, test, and deployment processes.
* Configure your CI/CD pipeline to run tests and linting before deployment.
* Use environment variables to configure your application in the CI/CD environment.
## 8. Database Workflow Design
* **Avoid Direct Changes in Production**: Once your application is live, refrain from making database changes using the Supabase Dashboard. Instead, utilize migration tools and enforce access control to prevent unauthorized modifications.
* **Multiple Environments**: Adopt a multi-stage development workflow (`local -> staging -> prod`). This approach allows for thorough testing and validation at each stage before changes are deployed to production.
* **Point-in-Time Recovery**: As your database grows, consider moving to Point-in-Time Recovery (PITR) to minimize the impact on database performance during maintenance and ensure data safety.
* **Database Migrations**: Use database migration tools to manage schema changes. This practice helps maintain consistency across different environments and simplifies version control.
* **Access Control**: Be mindful of who has access to your production environment. Limit access to experienced team members and set clear internal workflows to mitigate risks.
* **Security**: Regularly review and update your security measures. Ensure that tables with sensitive data have appropriate access levels and that database secrets and API keys are stored securely.
* **Performance Monitoring**: Utilize Supabase's observability tooling to monitor database performance and optimize queries, indexes, and connection management.
## 9. Additional Best Practices
* **Understand Shared Responsibilities:** When using Supabase, be aware of the shared responsibilities model. Supabase manages infrastructure, but you are responsible for application architecture, security, and data management.
* **Proper Indexing:** Essential for query optimization. Indices should be created based on common query patterns to reduce search time.
* **Load Testing**: Before deploying changes to production, perform load testing in a staging environment. Tools such as `k6` can simulate traffic and help identify potential bottlenecks.
* **Resource Upgrades**: Monitor resource usage and upgrade your database when necessary. For significant traffic surges, contact support in advance for assistance.
* **Database Optimization**: Regularly optimize your database by adding filters on large queries, using caching strategies, and managing connections efficiently.
* **Regular Backups:** Schedule regular backups of your database to protect against data loss.
* **Use of Postgres Features**: As Supabase is built around Postgres, understand and leverage Postgres features for performance and scalability.
## 10. Conclusion
By following these best practices, you can build robust, scalable, and secure applications with Supabase. Remember to stay up-to-date with the latest Supabase documentation and community resources to continuously improve your development practices.
@file ./supabase_code_examples.mdc
# Supabase Best Practices
This guide outlines the definitive best practices for developing with Supabase, ensuring your projects are secure, performant, and maintainable. Adhere to these rules for consistent, high-quality code.
## 1. SQL Style & Code Organization
Consistency is paramount. Follow these rules for all SQL schema, migrations, and functions.
### 1.1 Naming Conventions
- **Identifiers:** Use `snake_case` for all table, column, and function names. Names must begin with a letter and contain only letters, numbers, and underscores.
- **Keywords:** Always use lowercase for SQL keywords (e.g., `select`, `from`, `where`).
- **Table Names:** Prefer plural, `snake_case` names (e.g., `users`, `products`).
- **Column Names:** Prefer singular, `snake_case` names (e.g., `id`, `name`, `created_at`).
- **Foreign Keys:** Use `singular_table_name_id` (e.g., `user_id` for `users` table).
- **Triggers:** Prefix with a numeric order (e.g., `_200_update_timestamp`) as triggers run in lexicographical order.
❌ BAD
```sql
CREATE TABLE UserProfiles (
UserID INT PRIMARY KEY,
UserName VARCHAR(255)
);
SELECT UserID FROM UserProfiles;
```
✅ GOOD
```sql
CREATE TABLE user_profiles (
id bigint generated always as identity primary key,
user_name text not null,
user_id bigint references users (id) -- Example FK
);
SELECT id FROM user_profiles;
-- Trigger naming for ordered execution
CREATE TRIGGER _200_update_user_profile_timestamp
BEFORE UPDATE ON user_profiles
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
```
### 1.2 Formatting & Readability
- **Indentation:** Use consistent indentation for clauses and arguments.
- **Aliases:** Always use explicit `AS` for aliases. Make them meaningful.
- **Boolean Operators:** Place `AND`/`OR` at the beginning of the line for multi-line `WHERE` clauses.
- **Parentheses:** Align closing parentheses with the starting line of the expression.
❌ BAD
```sql
SELECT t.client_id, DATE(t.created_at) day
FROM telemetry t, users u
WHERE t.user_id = u.id AND t.submission_date > '2019-07-01'
GROUP BY 1, 2;
```
✅ GOOD
```sql
SELECT
t.client_id AS client_identifier,
DATE(t.created_at) AS created_day
FROM
telemetry AS t
INNER JOIN
users AS u ON t.user_id = u.id
WHERE
t.submission_date > '2019-07-01'
AND t.sample_id = '10'
GROUP BY
t.client_id,
created_day;
```
### 1.3 Common Table Expressions (CTEs)
- **Prefer CTEs:** Use CTEs (`WITH` clauses) for complex queries to improve readability and modularity over nested subqueries.
❌ BAD
```sql
SELECT
(SELECT COUNT(*) FROM orders WHERE user_id = u.id) AS order_count,
u.email
FROM
users AS u;
```
✅ GOOD
```sql
WITH user_order_counts AS (
SELECT
user_id,
COUNT(*) AS order_count
FROM
orders
GROUP BY
user_id
)
SELECT
u.email,
uoc.order_count
FROM
users AS u
LEFT JOIN
user_order_counts AS uoc ON u.id = uoc.user_id;
```
## 2. Data Modeling & Schema Design
Design your schema for clarity, integrity, and performance.
### 2.1 Primary Keys
- **Standard PK:** Every table *must* have an `id` column of type `bigint generated always as identity primary key`.
❌ BAD
```sql
CREATE TABLE products (
product_code text PRIMARY KEY,
name text
);
```
✅ GOOD
```sql
CREATE TABLE products (
id bigint generated always as identity primary key,
product_code text unique not null,
name text not null
);
```
### 2.2 Foreign Key Indexes
- **Always Index FKs:** PostgreSQL does *not* automatically index foreign keys. Always add an index to every foreign key column to prevent expensive lookups, especially for reverse relations.
❌ BAD
```sql
CREATE TABLE orders (
id bigint generated always as identity primary key,
user_id bigint references users (id)
);
-- Missing index on user_id
```
✅ GOOD
```sql
CREATE TABLE orders (
id bigint generated always as identity primary key,
user_id bigint references users (id)
);
CREATE INDEX ON orders (user_id);
```
### 2.3 Table Comments
- **Document Tables:** Always add a descriptive comment to each table using `COMMENT ON TABLE`.
❌ BAD
```sql
CREATE TABLE posts (
id bigint generated always as identity primary key,
title text
);
```
✅ GOOD
```sql
CREATE TABLE posts (
id bigint generated always as identity primary key,
title text not null,
content text
);
COMMENT ON TABLE posts IS 'Blog posts published by users.';
```
## 3. Security Best Practices
Security is non-negotiable. Implement these measures from day one.
### 3.1 Row-Level Security (RLS)
- **Enable RLS Everywhere:** Enable RLS on *every* table in your database, especially those exposed via API. This is your primary defense.
❌ BAD
```sql
CREATE TABLE sensitive_data (
id bigint generated always as identity primary key,
secret text
);
-- RLS NOT ENABLED
```
✅ GOOD
```sql
CREATE TABLE sensitive_data (
id bigint generated always as identity primary key,
secret text,
user_id uuid references auth.users(id)
);
ALTER TABLE sensitive_data ENABLE ROW LEVEL SECURITY;
CREATE POLICY select_own_secrets ON sensitive_data FOR SELECT USING (auth.uid() = user_id);
```
### 3.2 Function Security
- **Default to `SECURITY INVOKER`:** Functions should run with the permissions of the calling user. Use `SECURITY DEFINER` only when absolutely necessary and with extreme caution.
- **Explicit `search_path`:** If using `SECURITY DEFINER`, *always* set `search_path = ''` and use fully-qualified names (e.g., `public.table_name`) to prevent privilege escalation via malicious objects in other schemas.
❌ BAD
```sql
CREATE FUNCTION get_all_users()
RETURNS SETOF users
LANGUAGE plpgsql
SECURITY DEFINER -- Dangerous without search_path
AS $$
BEGIN
RETURN QUERY SELECT * FROM users;
END;
$$;
```
✅ GOOD
```sql
CREATE FUNCTION get_current_user_profile()
RETURNS SETOF user_profiles
LANGUAGE plpgsql
SECURITY INVOKER -- Default and safer
SET search_path = '' -- Always set, even for INVOKER for clarity
AS $$
BEGIN
RETURN QUERY SELECT * FROM public.user_profiles WHERE user_id = auth.uid();
END;
$$;
-- If SECURITY DEFINER is truly needed (rare):
CREATE FUNCTION admin_only_function()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = '' -- CRITICAL for SECURITY DEFINER
AS $$
BEGIN
-- Use fully qualified names for ALL objects
INSERT INTO public.audit_log (action) VALUES ('Admin function executed');
END;
$$;
```
### 3.3 Grant Permissions
- **Table-level `SELECT/DELETE`:** Grant `SELECT` and `DELETE` permissions at the table level.
- **Column-level `INSERT/UPDATE`:** Grant `INSERT` and `UPDATE` permissions at the column level for explicitness and to avoid optimizer issues.
- **Avoid Column-level `SELECT`:** This severely limits optimizations and functionality (e.g., `SELECT *`, `RETURNING *`).
- **Avoid Table-level `INSERT/UPDATE`:** Lacks explicitness.
❌ BAD
```sql
GRANT SELECT (id, name) ON users TO authenticated; -- Avoid column-level SELECT
GRANT INSERT ON users TO authenticated; -- Avoid table-level INSERT
```
✅ GOOD
```sql
GRANT SELECT ON users TO authenticated;
GRANT DELETE ON users TO authenticated;
GRANT INSERT (name, email) ON users TO authenticated;
GRANT UPDATE (name, email) ON users TO authenticated;
```
## 4. Performance & Query Optimization
Optimize your database interactions for speed and efficiency.
### 4.1 Prefer `LANGUAGE SQL` for Functions
- **Inlining:** Use `LANGUAGE sql` over `LANGUAGE plpgsql` for functions whenever possible. SQL functions can often be inlined by the query planner, leading to significant performance gains.
❌ BAD
```sql
CREATE FUNCTION add_one(a int)
RETURNS int
LANGUAGE plpgsql
AS $$
BEGIN
RETURN a + 1;
END;
$$;
```
✅ GOOD
```sql
CREATE FUNCTION add_one(a int)
RETURNS int
LANGUAGE sql
IMMUTABLE -- Declare as IMMUTABLE if results depend only on inputs
AS $$
SELECT a + 1;
$$;
```
### 4.2 Function Volatility
- **Immutable/Stable Defaults:** Declare functions as `IMMUTABLE` (returns same result for same inputs, no side effects) or `STABLE` (results change only within a single scan, no side effects) where appropriate. Default to `VOLATILE` only if the function modifies data or has external side effects. This allows PostgreSQL to optimize queries more effectively.
## 5. Testing & Linting
Ensure your database schema and functions are robust and error-free.
### 5.1 Database Testing
- **`supabase test db`:** Use the Supabase CLI (`supabase test db`) with `pgTAP` for comprehensive database unit and integration testing. Integrate this into your CI/CD pipeline.
### 5.2 Database Linting
- **`supabase db lint`:** Leverage `supabase db lint` (powered by `plpgsql_check`) to catch typing errors, unused variables, dead code, and potential SQL injection vulnerabilities early.
### 5.3 Type-Safe Query Builders
- **Kysely for Edge Functions:** For application code, especially in Edge Functions, use type-safe query builders like Kysely with `deno-postgres`. This provides compile-time guarantees and excellent autocompletion.
```typescript
// Example using Kysely in a Supabase Edge Function
import { Kysely, PostgresDialect } from 'kysely';
import { Pool } from 'https://deno.land/x/postgres@v0.17.0/mod.ts'; // Deno Postgres driver
interface Database {
users: {
id: number;
email: string;
created_at: Date;
};
posts: {
id: number;
user_id: number;
title: string;
};
}
const db = new Kysely<Database>({
dialect: new PostgresDialect({
pool: new Pool({
database: 'postgres',
hostname: Deno.env.get('DB_HOSTNAME'),
user: 'postgres',
password: Deno.env.get('DB_PASSWORD'),
port: 5432,
tls: { caCertificates: [Deno.env.get('DB_SSL_CERT')!] },
}, 1), // Single connection pool for Edge Functions
}),
});
// Type-safe query example
const user = await db.selectFrom('users')
.where('id', '=', 1)
.select(['id', 'email'])
.executeTakeFirst();
console.log(user?.email); // Autocompletion and type safety
```