Skip to main content
Prerequisite: You should have installed Docker and followed the Development setup guide.

Overview

NCT Hub utilizes Supabase for database management and authentication. This guide explains how to work efficiently with Supabase in the local development workflow.

Basic Commands

Starting Supabase

To start a local Supabase instance tailored for NCT Hub:
This command launches a local Supabase instance on your machine, accessible at http://localhost:8003.

Stopping Supabase

To stop the local Supabase instance:

Checking Status

To view the current URLs and status of your local Supabase instance:

Development Workflow

When developing for NCT Hub, you have several options to start your environment:
  1. Standard Approach: Start Next.js apps and Supabase separately.
  2. Enhanced Development Experience: Use the devx command for a streamlined setup.
    This command:
    • Stops any running Supabase instance and saves current data as backup
    • Installs all dependencies
    • Starts a new Supabase instance (using backed up data)
    • Starts all Next.js apps in development mode
  3. Fresh Database Setup: When switching branches with potential schema changes.
    This command:
    • Stops any running Supabase instance (without backup)
    • Installs all dependencies
    • Starts a new Supabase instance
    • Resets the database to use the latest schema
    • Starts all Next.js apps in development mode
Use bun sb:devrs when switching between branches that might have different database migrations to ensure your local database schema matches the branch you’re working on.

Syncing With Schema Changes

If you’re keeping your Next.js server running but need to reset your database to match the current branch’s schema:
This command will reset your local database to use the latest schema definitions and automatically regenerate TypeScript types.

Database Schema Management

Making Schema Changes

There are two approaches to modifying the database schema:

1. Using the Supabase UI

  1. Navigate to your local Supabase Studio at http://localhost:8003
  2. Make your changes through the UI
  3. Generate a migration file:
    This creates a migration file based on the differences between your current schema and the previous state.
Be cautious when using sb:diff for schema changes. If you rename columns or tables, the migration will drop the old ones and create new ones, which can result in data loss in production environments.

2. Creating Manual Migrations

For more control, you can create empty migration files and populate them manually:
This creates a new empty migration file in apps/db/supabase/migrations that you can edit to include your desired schema changes.

Applying Migrations

After creating a migration, apply it to your local database:
This same process is used to keep our production database up-to-date with the schema defined in the production branch.

Generating TypeScript Types

After schema changes, regenerate the TypeScript types to keep your code in sync with the database schema:
Alternatively, you can use the shorthand:
This step is automatically performed when running bun sb:reset, making it useful when catching up with a new branch’s schema.

Using Generated TypeScript Types

The Supabase-generated TypeScript types are available at packages/types/src/supabase.ts. These types are accessible to all apps that have the @ncthub/types package installed. You can use these types to ensure type safety when working with Supabase data:

Short-hand Type Access

For more convenient access to common table types, NCT Hub also provides short-hand type definitions in packages/types/src/db.ts. These are easier to use and remember than the full database type paths:
You can add your own short-hand types to db.ts for tables you frequently work with. This is especially useful for tables that have complex structures or need additional client-side properties. This ensures that your code correctly interacts with the database schema, reducing runtime errors and improving development experience.

Migration Files

All migration files are stored in apps/db/supabase/migrations. These files:
  • Contain SQL commands that create and modify the database schema
  • Are executed in order based on the timestamp prefix in their filenames
  • Include descriptive names after the timestamp to help developers understand their purpose
When contributing new migrations in a Pull Request, always add them after the latest migration file from the main branch. This maintains the correct execution order and prevents issues when syncing the production database.

Local Authentication

A local mail server (InBucket) is automatically set up by Supabase to handle authentication emails. You can access it at http://localhost:8004. With InBucket, you can:
  • Receive all authentication emails sent by your local Supabase instance
  • Test any email combination without needing actual mail delivery
  • View password reset links, confirmation emails, and other authentication flows
  • Troubleshoot email templates and content
This makes it easy to test different authentication scenarios without configuring a real email service or waiting for actual email delivery. Five seed accounts are pre-configured for local development:
  1. local@tuturuuu.com
  2. user1@tuturuuu.com
  3. user2@tuturuuu.com
  4. user3@tuturuuu.com
  5. user4@tuturuuu.com
These accounts are already set up with the necessary data, allowing you to quickly test the app’s functionality. However, you can register any new email address and the authentication emails will be captured by InBucket for you to inspect.

Further Information

For more details about Supabase CLI usage, refer to the Supabase CLI documentation.

Row Level Security (RLS)

Row Level Security (RLS) is a powerful Postgres feature that allows you to control access to rows in a database table based on the user making the request. In NCT Hub, we use RLS extensively to ensure data security.

Enabling RLS

RLS should be enabled on all tables in exposed schemas (like public). When creating tables through the Supabase UI, RLS is enabled by default. For tables created using SQL, you need to explicitly enable RLS:

Creating RLS Policies

Policies define the conditions under which users can access or modify data. Here are some common patterns used in NCT Hub:

Organization-based Access

In NCT Hub, most resources belong to an organization (workspace). Here’s how to create policies for organization-based access:

Role-based Access

For more granular control based on user roles:

Performance Optimization for RLS

For better performance in your RLS policies:
  1. Wrap function calls in subqueries:
  2. Use security definer functions for complex access logic:
  3. Add explicit filters in your queries even when you have RLS:

Testing RLS Policies

To test your RLS policies during local development:
  1. Create a SQL file in apps/db/supabase/tests with your test cases
  2. Use the bun sb:test command to run the tests
Example test file:

Database Triggers

Triggers in Postgres allow you to automatically execute a function when a specified database event occurs (INSERT, UPDATE, DELETE). In NCT Hub, we use triggers for various purposes like:
  • Maintaining audit logs
  • Syncing data between tables
  • Enforcing complex business rules

Creating Triggers

Here’s how to create a trigger in your NCT Hub development workflow:
  1. First, create a trigger function:
  1. Then, create the trigger:

Common Triggers in NCT Hub

Audit Logging

Automated Timestamps

Testing Triggers

You can test triggers by running SQL commands in the local Supabase instance and verifying the results:

Seeding Your Database

Database seeding is the process of populating your database with initial data. In NCT Hub, we use seeding to:
  1. Create test users and workspaces for local development
  2. Initialize lookup tables with standard values
  3. Ensure a consistent starting point for all developers

Seed Files Location

In NCT Hub, seed files are stored in apps/db/supabase/seed.sql. This file is automatically executed when you run bun sb:reset or start a fresh Supabase instance.

Real Examples from NCT Hub’s Seed File

Let’s look at some real examples from NCT Hub’s seed.sql file:

1. Authentication Users

The seed file creates five default test users with pre-set passwords:
All seed users have the same password: password123, making it easy to log in for testing.

2. Workspaces

The seed creates several workspaces for testing different scenarios:

3. Workspace Members and Roles

The seed also sets up relationships between users and workspaces with different roles:

4. Workspace Features Configuration

The seed file configures workspace features using secrets:

5. Domain-specific Data

The seed includes domain-specific data for different workspace types. For example, healthcare data:

Creating Seed Data

Here’s how to create and modify seed data:
  1. Edit the apps/db/supabase/seed.sql file
  2. Add SQL statements to insert your data
  3. Run bun sb:reset to apply the seed data
Example seed data format:

Creating a Custom Seed File

Sometimes you might want to create a custom seed file for specific testing scenarios:
  1. Create a new SQL file in the apps/db/supabase directory
  2. Add your custom seed data
  3. Run it with the Supabase CLI:

Exporting Current Data as Seed

You can also export your current database data to use as seed data:
This is helpful when you’ve set up data manually and want to preserve it for future development environments. For NCT Hub development, we recommend:
  1. Start with a fresh database: bun sb:reset
  2. Make changes through the UI or your app
  3. When you’re satisfied, export the data: bun supabase db dump --data-only > apps/db/supabase/new_seed.sql
  4. Edit the generated SQL to keep only what you need
  5. Update the main seed.sql file with your changes
  6. Test by running bun sb:reset again

AI Integration with Vercel AI SDK

NCT Hub uses Vercel’s AI SDK for its AI features, utilizing structured data generation capabilities that integrate with Supabase. This section covers how to work with AI features in the development workflow.

Overview of AI SDK in NCT Hub

The AI SDK standardizes integrating various AI models across supported providers into NCT Hub applications. It enables structured data generation, tool calling, and streaming responses to create rich AI-powered features. The main libraries used are:
  • ai - Core Vercel AI SDK package
  • @ai-sdk/google - Provider-specific integration for Google models
  • @ncthub/supabase - Supabase client with NCT Hub-specific utilities

Generating Structured Data

NCT Hub uses the AI SDK’s structured data generation capabilities to create typed responses from AI models. This approach ensures type safety and consistent data structures for features like:
  • Flashcards generation
  • Quiz generation
  • Learning plans
  • Task management

Example: Flashcard Generation

The structured data pattern used in NCT Hub follows this workflow:
  1. Define a schema using Zod
  2. Connect to Supabase for authentication and workspace validation
  3. Generate structured data using the AI SDK
  4. Stream the response to the client
Here’s an example from NCT Hub’s codebase:

Available Models

NCT Hub supports multiple AI models through Vercel AI SDK. You can define which models are available in your application by updating the models.ts file in the packages/ai directory:

Creating Custom Schema Types

To create new structured data types for AI generation, add your schema definition to the packages/ai/src/object/types.ts file:

Integration with Supabase

NCT Hub’s AI features leverage Supabase for:
  1. Authentication - Validating users before making AI requests
  2. Authorization - Checking workspace permissions via workspace_secrets
  3. Feature Flags - Using workspace_secrets to enable/disable AI features per workspace
  4. Storage - Storing AI-generated content for later use
To enable AI features for a workspace, ensure the appropriate flags are set in the workspace_secrets table:

Testing AI Features Locally

When testing AI features in your local environment:
  1. Ensure you have the required API keys set in your .env.local file:
  2. Verify the workspace has the necessary feature flags enabled in your local database
  3. Use the AI-enabled accounts from the seed data (local@tuturuuu.com) as they often have additional permissions

Error Handling

When integrating AI features, implement proper error handling to account for:
  1. Missing API keys
  2. Model unavailability
  3. Invalid user input
  4. Exceeded token limits
Example error handling pattern used in NCT Hub: