> ## Documentation Index
> Fetch the complete documentation index at: https://codinitdev-mintlify-update-changelog-codinit-dev-90028.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Supabase Integration

> Complete Supabase integration with database operations, authentication, real-time subscriptions, and TypeScript support

CodinIT provides Supabase integration, enabling you to build full-stack applications with databases, user login systems, live data updates, and server functions.

<Note>
  **What is Supabase?** Supabase is a service that provides a database (a place to store your app's data), user authentication (login/signup systems), and other backend features—all without you needing to set up your own servers.
</Note>

This integration goes beyond basic database connectivity to include advanced features like Row Level Security (RLS), automated migrations, and TypeScript type generation.

## Overview

The Supabase integration in CodinIT offers powerful database capabilities with easy-to-use tools:

<CardGroup cols={3}>
  <Card title="PostgreSQL Database" icon="database">
    A hosted database to store all your app's information (users, posts, orders, etc.)
  </Card>

  <Card title="Authentication" icon="shield">
    Ready-made login systems including "Sign in with Google" and email/password
  </Card>

  <Card title="Real-time" icon="zap">
    Your app updates instantly when data changes—no page refresh needed
  </Card>
</CardGroup>

### Key features

* **Automated migrations**: Database changes are tracked and can be undone if something goes wrong
* **Row Level Security (RLS)**: Rules that control who can see or edit specific data (for example, users can only see their own orders)
* **TypeScript integration**: Your code editor knows exactly what data types to expect, reducing errors
* **Real-time subscriptions**: Your app automatically updates when data changes—like seeing new messages appear without refreshing
* **Authentication flows**: Complete user registration, login, and session management
* **Edge functions**: Small programs that run on Supabase's servers to handle tasks like sending emails or processing payments
* **File storage**: Built-in file upload and management for images, documents, and other files

<Callout type="info">
  **Default choice**: Supabase is the recommended database solution for CodinIT projects requiring advanced database
  features, authentication, or real-time capabilities.
</Callout>

## Setup and configuration

### Connecting to Supabase

<Steps>
  <Step title="Create Supabase Account">Visit [Supabase](https://supabase.com/) and create a free account</Step>
  <Step title="Create New Project">Click "New Project" and fill in your project details</Step>
  <Step title="Get Connection Details">Navigate to Settings > API to get your project URL and API keys</Step>

  <Step title="Configure in CodinIT">
    Use the Supabase connection prompt in chat: "Connect to Supabase in the chat box"
  </Step>

  <Step title="Provide Credentials">Share your Supabase URL and anon key when prompted</Step>
</Steps>

### Environment variables

<Note>
  **What are environment variables?** These are secret settings stored outside your code. They keep sensitive information like passwords and API keys safe, and let you use different settings for testing vs. your live app.
</Note>

CodinIT automatically creates the necessary environment variables:

```bash theme={null}
VITE_SUPABASE_URL=your_supabase_project_url
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
```

<Callout type="warning">
  **Security note**: Never share or publish your Supabase service role key. The "anon key" is safe to use in your app's front-end code.
</Callout>

### Connection verification

Once connected, CodinIT will:

* ✅ Confirm successful connection
* ✅ Set up environment variables
* ✅ Prepare for database operations

If connection fails, you'll receive guidance to:

* Verify your API keys
* Check project permissions
* Ensure network connectivity

## Database operations

### Creating tables and schemas

<Note>
  **What is a table?** A table is like a spreadsheet in your database. Each table stores one type of information (like "users" or "orders"), with rows for each item and columns for each piece of data (like "name" or "email").
</Note>

CodinIT automatically generates SQL migrations for database changes:

**Example Migration Creation:**

```sql theme={null}
-- Create users table migration
CREATE TABLE users (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  email text UNIQUE NOT NULL,
  created_at timestamptz DEFAULT now()
);
```

### Row Level Security (RLS)

<Note>
  **What is Row Level Security?** RLS is like a security guard for your data. It automatically filters what each user can see or change. For example, you can set rules so users only see their own orders, not everyone else's.
</Note>

All tables automatically get RLS enabled with appropriate policies:

```sql theme={null}
-- Enable RLS (turn on the security guard)
ALTER TABLE users ENABLE ROW LEVEL SECURITY;

-- Create a rule: users can only read their own data
CREATE POLICY "Users can read own data"
  ON users
  FOR SELECT
  TO authenticated
  USING (auth.uid() = id);
```

### Data operations

**Querying data (getting information from your database):**

```typescript theme={null}
// Get all active users from the database
const { data: users } = await supabase.from('users').select('*').eq('status', 'active');
```

**Real-time subscriptions (automatically update when data changes):**

```typescript theme={null}
// Listen for any changes to the users table
// When someone signs up or updates their profile, your app knows immediately
const channel = supabase
  .channel('users')
  .on(
    'postgres_changes',
    {
      event: '*',
      schema: 'public',
      table: 'users',
    },
    (payload) => {
      console.log('Change received!', payload);
    },
  )
  .subscribe();
```

## Authentication System

### User Registration and Login

CodinIT implements complete authentication flows using Supabase Auth:

**Supported Authentication Methods:**

* Email and password registration
* Social provider login (Google, GitHub, etc.)
* Magic link authentication
* Password reset functionality

**Example Implementation:**

```typescript theme={null}
// Sign up new user
const { data, error } = await supabase.auth.signUp({
  email: 'user@example.com',
  password: 'securepassword',
});

// Sign in existing user
const { data, error } = await supabase.auth.signInWithPassword({
  email: 'user@example.com',
  password: 'securepassword',
});
```

### Session Management

**Automatic Session Handling:**

* JWT token management
* Automatic token refresh
* Session persistence across page reloads
* Secure logout functionality

**Protected Routes:**

```typescript theme={null}
// Route protection example
const {
  data: { user },
} = await supabase.auth.getUser();
if (!user) {
  // Redirect to login
}
```

### User Profile Management

**Profile Data:**

* User metadata storage
* Avatar management
* Custom user fields
* Profile update functionality

<Callout type="info">
  **Email Confirmation**: By default, email confirmation is disabled for easier development. Enable it in production for
  security.
</Callout>

## TypeScript Integration

### Auto-Generated Types

CodinIT generates TypeScript types from your Supabase schema:

**Type Generation:**

```typescript theme={null}
// Auto-generated types from your database schema
export interface Database {
  public: {
    Tables: {
      users: {
        Row: {
          id: string;
          email: string;
          created_at: string;
        };
        Insert: {
          id?: string;
          email: string;
          created_at?: string;
        };
        Update: {
          id?: string;
          email?: string;
          created_at?: string;
        };
      };
    };
  };
}
```

### Type-Safe Queries

**Full Type Safety:**

```typescript theme={null}
// Type-safe database operations
const { data, error } = await supabase
  .from('users') // Fully typed table name
  .select('id, email') // Typed column selection
  .eq('status', 'active') // Typed filter conditions
  .returns<User[]>(); // Explicit return type
```

## Advanced Features

### Real-Time Subscriptions

**Live Data Updates:**

```typescript theme={null}
const channel = supabase
  .channel('realtime-users')
  .on(
    'postgres_changes',
    {
      event: 'INSERT',
      schema: 'public',
      table: 'users',
    },
    (payload) => {
      console.log('New user:', payload.new);
    },
  )
  .subscribe();
```

### File Storage

**File Upload and Management:**

```typescript theme={null}
// Upload files to Supabase Storage
const { data, error } = await supabase.storage.from('avatars').upload('user-avatar.jpg', file);

// Get public URL
const {
  data: { publicUrl },
} = supabase.storage.from('avatars').getPublicUrl('user-avatar.jpg');
```

### Edge Functions

**Serverless API Endpoints:**

```typescript theme={null}
// Call Supabase Edge Functions
const { data, error } = await supabase.functions.invoke('my-function', {
  body: { key: 'value' },
});
```

## Best Practices

### Database Design

**Schema Best Practices:**

* Use UUID primary keys with `gen_random_uuid()`
* Enable RLS on all tables
* Create appropriate indexes for query performance
* Use foreign key constraints for data integrity

**Migration Strategy:**

* One logical change per migration
* Include descriptive comments in SQL
* Test migrations on development data
* Plan rollback strategies

### Security Considerations

**RLS Policies:**

* Always enable RLS on user-facing tables
* Create policies for each operation type (SELECT, INSERT, UPDATE, DELETE)
* Test policies with different user roles
* Avoid overly permissive policies

**Authentication Security:**

* Use HTTPS for all authentication flows
* Implement proper session management
* Validate user input on both client and server
* Regularly rotate API keys

## Troubleshooting

<AccordionGroup>
  <Accordion title="Connection Issues" icon="wifi-off">
    ### Database Connection Problems

    **Common Issues:**

    * Verify API keys are correct and have proper permissions
    * Check that the Supabase project is active and not paused
    * Ensure network connectivity to Supabase servers
    * Confirm environment variables are properly set

    **Solutions:**

    * Regenerate API keys in Supabase dashboard
    * Check Supabase project status and billing
    * Verify firewall settings allow Supabase connections
    * Test connection with a simple query
  </Accordion>

  <Accordion title="Migration Errors" icon="alert-triangle">
    ### Database Migration Failures

    **Common Issues:**

    * SQL syntax errors in migration files
    * Foreign key constraint violations
    * RLS policy conflicts
    * Insufficient permissions

    **Solutions:**

    * Validate SQL syntax before applying migrations
    * Check existing data before adding constraints
    * Review RLS policies for conflicts
    * Use Supabase dashboard for manual testing
  </Accordion>

  <Accordion title="Authentication Problems" icon="shield-x">
    ### Auth Flow Issues

    **Common Issues:**

    * Email confirmation settings
    * Social provider configuration
    * JWT token expiration
    * Password policy conflicts

    **Solutions:**

    * Check email confirmation settings in Supabase
    * Verify social provider API keys
    * Implement proper token refresh logic
    * Review password requirements
  </Accordion>

  <Accordion title="Performance Issues" icon="gauge">
    ### Query Performance Problems

    **Common Issues:**

    * Missing database indexes
    * Inefficient query patterns
    * Large result sets
    * Real-time subscription overhead

    **Solutions:**

    * Add appropriate indexes for query patterns
    * Optimize query structure and filtering
    * Implement pagination for large datasets
    * Limit real-time subscriptions to necessary data
  </Accordion>
</AccordionGroup>

## Migration Examples

### From Local Database to Supabase

**Migration Process:**

1. Export existing data from local database
2. Create Supabase tables with proper schemas
3. Import data using Supabase client or SQL
4. Update application to use Supabase URLs
5. Test all functionality with migrated data

### Schema Evolution

**Safe Schema Changes:**

```sql theme={null}
-- Adding a new column with default
ALTER TABLE users ADD COLUMN last_login timestamptz;

-- Adding an index for performance
CREATE INDEX idx_users_email ON users(email);

-- Safe constraint addition
ALTER TABLE users ADD CONSTRAINT email_format
  CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');
```

<Callout type="warning">
  **Data Safety**: Always backup data before making schema changes. Test migrations on development data first.
</Callout>

<Callout type="tip">
  **Development Workflow**: Use Supabase's dashboard for quick testing and data exploration during development.
</Callout>
