# CI/CD Pipelines Source: https://docs.rmitnct.club/ci-cd-pipelines Understanding NCTHub CI/CD pipelines and automated workflows. **Prerequisite**: You should have read the [Monorepo Architecture](/monorepo-architecture) page to understand the basic structure of the codebase. ## Overview NCTHub uses GitHub Actions for continuous integration and continuous deployment (CI/CD) across our monorepo. These automated workflows help us maintain code quality, run tests, and deploy our applications to various environments. This page documents the key CI/CD pipelines used in the NCTHub platform and how they support our development workflow. ## Workflow Categories Our GitHub Actions workflows are organized into several categories: ### 1. Application Deployments Automated deployments to Vercel for our Next.js applications: * Production deployments (from `production` branch) * Preview deployments (from push events to non-production branches) ### 2. Database Migrations Supabase database migration workflows for different environments: * Production database migrations * Staging database migrations * Type generation verification ### 3. Package Publishing Workflows that publish our shared packages to NPM, GitHub Packages, and JSR: * Types package * UI package * Supabase client package * ESLint config package * TypeScript config package * AI package ### 4. Quality Assurance Workflows that ensure code quality: * Unit tests * Prettier formatting checks * CodeQL security scanning * CodeCov code coverage reporting ## Key Workflows ### Application Deployments We use Vercel for deploying our Next.js applications. The main deployment workflows are: #### Production Deployments When code is pushed to the `production` branch, applications are automatically deployed to production: ```yaml theme={null} name: Vercel Platform Production Deployment env: VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PLATFORM_PROJECT_ID }} TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} TURBO_TEAM: ${{ secrets.TURBO_TEAM }} NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.PRODUCTION_SUPABASE_URL }} NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.PRODUCTION_SUPABASE_ANON_KEY }} SUPABASE_SERVICE_KEY: ${{ secrets.PRODUCTION_SUPABASE_SERVICE_KEY }} on: push: branches: - production workflow_dispatch: jobs: Deploy-Production: runs-on: ubuntu-latest steps: # Setup and optimization steps... - name: Check for newer commits id: check_commits run: | git fetch origin production LATEST_COMMIT=$(git rev-parse origin/production 2>/dev/null || echo "") CURRENT_COMMIT=${GITHUB_SHA} if [ -n "$LATEST_COMMIT" ] && [ "$LATEST_COMMIT" != "$CURRENT_COMMIT" ]; then echo "Newer commit found on production branch. Skipping build." echo "skip_build=true" >> $GITHUB_OUTPUT else echo "This is the latest commit. Proceeding with build." echo "skip_build=false" >> $GITHUB_OUTPUT fi # Deployment steps, only run if no newer commits found - name: Pull Vercel Environment Information if: steps.check_commits.outputs.skip_build != 'true' run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }} - name: Build Project Artifacts if: steps.check_commits.outputs.skip_build != 'true' run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }} - name: Deploy Project Artifacts to Vercel if: steps.check_commits.outputs.skip_build != 'true' run: vercel deploy --archive=tgz --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }} ``` We have separate production deployment workflows for each application: * `vercel-production-hub.yaml` - Main web app All production workflows follow the same pattern but deploy to different Vercel projects, each with its own environment variables and project ID. #### Preview Deployments For non-production branches, we create preview deployments that allow developers to see their changes live before merging: ```yaml theme={null} name: Vercel Platform Preview Deployment env: VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PLATFORM_PROJECT_ID }} TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} TURBO_TEAM: ${{ secrets.TURBO_TEAM }} on: push: branches-ignore: - production workflow_dispatch: jobs: Deploy-Preview: runs-on: ubuntu-latest steps: # Setup and optimization steps... - name: Check for newer commits id: check_commits run: | CURRENT_BRANCH=${GITHUB_REF#refs/heads/} git fetch origin $CURRENT_BRANCH # Skip if newer commits exist on the same branch # ... (commit checking logic) # Deployment steps, with conditional execution - name: Pull Vercel Environment Information if: steps.check_commits.outputs.skip_build != 'true' run: vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }} - name: Build Project Artifacts if: steps.check_commits.outputs.skip_build != 'true' run: vercel build --token=${{ secrets.VERCEL_TOKEN }} - name: Deploy Project Artifacts to Vercel if: steps.check_commits.outputs.skip_build != 'true' run: vercel deploy --archive=tgz --prebuilt --token=${{ secrets.VERCEL_TOKEN }} ``` Preview deployments are set up for all our applications, providing a temporary deployment URL for each branch. ### Database Migrations We use Supabase for our database, and have automated workflows for managing database migrations: #### Production Database Migrations ```yaml theme={null} name: Supabase CI on: # push: # branches: # - production workflow_dispatch: jobs: deploy: name: Migrate production database timeout-minutes: 15 runs-on: ubuntu-latest env: SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }} SUPABASE_DB_PASSWORD: ${{ secrets.PRODUCTION_DB_PASSWORD }} PRODUCTION_PROJECT_ID: ${{ secrets.PRODUCTION_PROJECT_ID }} PRODUCTION_DB_URL: ${{ secrets.PRODUCTION_DB_URL }} steps: - uses: actions/checkout@v4 - uses: supabase/setup-cli@v1 with: version: latest - name: Deploy migrations to production run: | cd apps/db supabase link --project-ref ${{ env.PRODUCTION_PROJECT_ID }} supabase db push ``` This workflow is manually triggered (via `workflow_dispatch`) to deploy database migrations to production environment. This gives us control over when migrations are applied to production. #### Supabase Type Verification We ensure that generated TypeScript types match our database schema: ```yaml theme={null} name: Supabase CI on: push: workflow_dispatch: jobs: deploy: name: Verify generated types timeout-minutes: 15 runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: supabase/setup-cli@v1 with: version: latest - run: supabase init - run: supabase db start - name: Verify generated types match Postgres schema run: | supabase gen types typescript --local > schema.gen.ts if ! git diff --ignore-space-at-eol --exit-code --quiet schema.gen.ts; then echo "Detected uncommitted changes after build. See status below:" git diff exit 1 fi ``` This workflow runs on every push, ensuring that our TypeScript types are always in sync with the database schema. ### Package Publishing We publish several packages to make our code reusable across projects. Here's an example workflow for the types package: ```yaml theme={null} name: Release @ncthub/types package on: pull_request: types: [closed] paths: - 'packages/types/package.json' - 'packages/types/jsr.json' workflow_dispatch: jobs: check-version-bump: if: github.event.pull_request.merged == true && contains(github.event.pull_request.title, 'chore(@ncthub/types)') runs-on: ubuntu-latest outputs: should_release: ${{ steps.check.outputs.should_release }} steps: - id: check run: echo "should_release=true" >> $GITHUB_OUTPUT build: needs: check-version-bump if: needs.check-version-bump.outputs.should_release == 'true' runs-on: ubuntu-latest # Build steps publish-jsr: needs: [build] runs-on: ubuntu-latest permissions: contents: read id-token: write steps: # Setup steps - name: Publish package to JSR working-directory: packages/types run: bunx jsr publish publish-npm: needs: [build] runs-on: ubuntu-latest permissions: packages: write contents: read steps: # Setup steps - name: Publish package working-directory: packages/types run: bun publish env: NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} ``` Our package publishing workflows follow a pattern: 1. Check for a version bump in the package.json and ensure the PR title follows our convention 2. Build and test the package 3. Publish to multiple registries (JSR, GitHub Packages, NPM) We have similar workflows for other packages: * `release-ui-package.yaml` * `release-ai-package.yaml` * `release-supabase-package.yaml` * `release-eslint-config-package.yaml` * `release-typescript-config-package.yaml` ### Quality Assurance We use several workflows to ensure code quality: #### Unit Tests ```yaml theme={null} name: Test on: push: branches: ['main'] pull_request: jobs: build: name: Unit Tests timeout-minutes: 15 runs-on: ubuntu-latest strategy: matrix: node-version: [22] env: # Use Vercel Remote Caching TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} TURBO_TEAM: ${{ secrets.TURBO_TEAM }} # Configure environment variables NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.NEXT_PUBLIC_SUPABASE_URL }} NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.NEXT_PUBLIC_SUPABASE_ANON_KEY }} SUPABASE_SERVICE_KEY: ${{ secrets.SUPABASE_SERVICE_KEY }} steps: # Setup steps - name: Test run: bun run test ``` This workflow runs on every push to main and on all pull requests, ensuring our tests pass. #### Prettier Formatting We enforce consistent code formatting with Prettier using an automated workflow that can create PRs for formatting fixes: ```yaml theme={null} name: Prettier Format Check on: push: workflow_dispatch: jobs: format: name: Prettier Check timeout-minutes: 10 runs-on: ubuntu-latest permissions: contents: write pull-requests: write strategy: matrix: node-version: [23] steps: # Setup steps - name: Check Prettier formatting id: check-format run: bun format:check || echo "format_failed=true" >> $GITHUB_OUTPUT - name: Apply Prettier fixes if: steps.check-format.outputs.format_failed == 'true' run: bun format - name: Check for changes if: steps.check-format.outputs.format_failed == 'true' id: git-check run: | if [[ -n $(git status --porcelain) ]]; then echo "changes=true" >> $GITHUB_OUTPUT else echo "changes=false" >> $GITHUB_OUTPUT fi - name: Create Pull Request if: steps.git-check.outputs.changes == 'true' id: create-pr uses: peter-evans/create-pull-request@v7 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: 'style: apply prettier formatting' title: 'style: apply prettier formatting for ${{ github.ref_name }}' body: | This PR fixes code formatting issues using Prettier. Auto-generated by the Prettier Format Check workflow. branch: fix/prettier-formatting-${{ github.ref_name }} base: ${{ github.ref_name }} delete-branch: true ``` This workflow not only checks code formatting but also: 1. Automatically applies Prettier fixes if formatting issues are found 2. Creates a pull request with the fixes 3. Adds informative comments to existing PRs if formatting issues are detected ## Workflow Organization Our GitHub Actions workflows are all defined in the `.github/workflows` directory of the repository. They follow a consistent naming convention: ### Application Deployment Workflows * `vercel-production-*.yaml`: Production deployment workflows for each application * Example: `vercel-production-hub.yaml` * `vercel-preview-*.yaml`: Preview deployment workflows for each application * Example: `vercel-preview-hub.yaml` ### Database Workflows * `supabase-production.yaml`: Production database migrations * `supabase-staging.yaml`: Staging database migrations * `supabase-types.yaml`: TypeScript type verification ### Package Publishing Workflows * `release-*-package.yaml`: Package publishing workflows * Example: `release-ui-package.yaml`, `release-types-package.yaml` ### Quality Assurance Workflows * `turbo-unit-tests.yaml`: Unit test workflow * `prettier-check.yaml`: Code formatting workflow * `codecov.yaml`: Code coverage reporting * `codeql.yml`: Security scanning ### Other Utilities * `check-and-bump-versions.yaml`: Automated dependency version management * `external-internal-packages.yaml`: Managing external vs internal dependencies ## Common Workflow Patterns Our workflows follow several common patterns: ### 1. Conditional Execution Many workflows check if they should run based on certain conditions: ```yaml theme={null} - name: Check for newer commits id: check_commits run: | # Logic to determine if build should be skipped echo "skip_build=false" >> $GITHUB_OUTPUT - name: Next step if: steps.check_commits.outputs.skip_build != 'true' run: echo "Only runs if no newer commits were found" ``` ### 2. Dependency Caching Most workflows use caching to speed up builds: ```yaml theme={null} - name: Cache turbo build setup uses: actions/cache@v4 with: path: .turbo key: ${{ runner.os }}-turbo-${{ github.sha }} restore-keys: | ${{ runner.os }}-turbo- - name: Setup bun uses: oven-sh/setup-bun@v2 with: bun-version: '1.3.14' - name: Use Node.js 25 uses: actions/setup-node@v4 with: node-version: 25 ``` ### 3. PR-based Publishing Package releases are triggered by merged PRs with specific title patterns: ```yaml theme={null} on: pull_request: types: [closed] paths: - 'packages/types/package.json' # ... jobs: check-version-bump: if: github.event.pull_request.merged == true && contains(github.event.pull_request.title, 'chore(@ncthub/types)') # ... ``` ## Environment Variables and Secrets Our workflows use several environment variables and secrets stored in GitHub: * `VERCEL_TOKEN`: For deploying to Vercel * `VERCEL_ORG_ID`: Vercel organization ID * `VERCEL_*_PROJECT_ID`: Project-specific Vercel IDs * `SUPABASE_ACCESS_TOKEN`: For authenticating with Supabase * `*_SUPABASE_URL`, `*_SUPABASE_ANON_KEY`, `*_SUPABASE_SERVICE_KEY`: Environment-specific Supabase credentials * `NPM_TOKEN`: For publishing to NPM * `TIPTAP_PRO_TOKEN`: For accessing Tiptap Pro packages * `TURBO_TOKEN` and `TURBO_TEAM`: For Turborepo remote caching Never hard-code sensitive information in workflow files. Always use GitHub Secrets for API tokens, passwords, and other sensitive data. ## Remote Caching with Turborepo We leverage Turborepo's remote caching feature in our CI pipelines to speed up builds: ```yaml theme={null} env: # Use Vercel Remote Caching TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} TURBO_TEAM: ${{ secrets.TURBO_TEAM }} ``` This allows our CI jobs to reuse cached build artifacts from previous runs, significantly reducing build times. For large monorepos like ours, this can reduce CI times from 20+ minutes to just a few minutes when the cache is warm. ## Best Practices When working with our CI/CD pipelines, follow these best practices: ### 1. Test Workflows Locally Before creating a new workflow, test it locally using [act](https://github.com/nektos/act) or similar tools. ```bash theme={null} # Install act brew install act # Run a specific workflow locally act -W .github/workflows/your-workflow.yaml ``` ### 2. Keep Workflows Focused Each workflow should have a single responsibility. Split complex workflows into smaller, more focused ones. ### 3. Reuse Common Steps Use composite actions or job templates to reuse common steps across workflows. ### 4. Monitor Workflow Performance Regularly check workflow runs for performance issues and optimize as needed: 1. Use GitHub's workflow visualization to identify bottlenecks 2. Implement caching for dependencies and build artifacts 3. Run jobs in parallel when possible 4. Skip unnecessary steps with conditional execution ### 5. Document Workflow Changes When making significant changes to workflows, document them in pull request descriptions and update this documentation. ## Troubleshooting ### Common Issues #### 1. Workflow Timeouts If a workflow times out, it might be due to: * Inefficient build process * Missing cache configuration * Network issues with external services Try adding or improving caching strategies and optimizing build steps. #### 2. Failed Deployments When deployments fail, check: * Build logs for errors * Environment variable configuration * Access tokens and permissions #### 3. Authentication Issues For authentication problems with NPM, GitHub Packages, or Vercel: * Verify token permissions * Ensure tokens are not expired * Check that the token is correctly configured in GitHub Secrets ## Creating New Workflows When creating a new workflow, use this checklist: 1. **Naming Convention**: Follow the established naming patterns 2. **Trigger Conditions**: Define when the workflow should run 3. **Environment Variables**: Include all necessary secrets and variables 4. **Optimizations**: Add caching and conditional execution 5. **Error Handling**: Include appropriate error handling and notifications 6. **Documentation**: Add comments within the workflow file and update documentation ## Further Resources * [GitHub Actions Documentation](https://docs.github.com/en/actions) * [Vercel CLI Documentation](https://vercel.com/docs/cli) * [Supabase CLI Documentation](https://supabase.com/docs/guides/cli) * [Turborepo Documentation](https://turbo.build/repo/docs/ci) * [bun Workspace Documentation](https://bun.sh/docs/install/workspaces) # Development Source: https://docs.rmitnct.club/development Learn how to preview changes locally. **Prerequisite**: You should have installed [Node.js](https://nodejs.org) (version 20 or higher). ## Installation Step 1. Install [bun](https://bun.sh/docs/installation) on your machine (if you don't already have it yet), by running the following command: **macOS/Linux:** ```bash theme={null} curl -fsSL https://bun.sh/install | bash ``` **Windows:** ```bash theme={null} powershell -c "irm bun.sh/install.ps1 | iex" ``` ## Why Bun? We chose bun as our runtime and package manager based on its [design goals](https://bun.sh/docs#design-goals), which align perfectly with our platform's needs: * **4x Faster Startup**: Bun processes start significantly faster than Node.js, improving development experience and CI/CD performance * **Built-in TypeScript & JSX Support**: No need for additional transpilation setup - bun natively executes `.ts`, `.tsx`, and `.jsx` files * **All-in-One Toolkit**: Combines runtime, package manager, bundler, test runner, and script runner in a single executable * **Web Standards Compatibility**: Implements modern Web APIs like `fetch`, `WebSocket`, and `ReadableStream` out of the box * **Node.js Compatibility**: Drop-in replacement for Node.js with full compatibility for existing projects * **Better Performance**: Powered by JavaScriptCore engine with reduced memory usage and faster execution These benefits make bun an ideal choice for our monorepo architecture and development workflow. Step 2. **Configure Tiptap Pro Registry:** This step is no longer needed. Step 3. After configuring Tiptap Pro registry, you can install all dependencies by running the following command: ```bash standard theme={null} bun install ``` ```bash short-hand theme={null} bun i ``` To complete the initial setup, please restart your IDE so that it can recognize the newly installed dependencies. Additionally, some recommended VS Code Extensions may only work after restarting your IDE. If you're using VS Code, you can install following the recommended extensions that will help you with the development process: [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint), [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode), [Vitest](https://marketplace.visualstudio.com/items?itemName=vitest.explorer), [Tailwind CSS IntelliSense](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss), [Version Lens](https://marketplace.visualstudio.com/items?itemName=pflannery.vscode-versionlens), [Error Lens](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens), [Pretty TypeScript Errors](https://marketplace.visualstudio.com/items?itemName=YoavBls.pretty-ts-errors), [Material Icon Theme](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme). ## Development ### Start Next.js apps To develop all apps and packages (without requiring a local setup), run the following command: ```bash bun theme={null} bun dev ``` This command will start all Next.js apps in development mode. You can access the apps by visiting the following URL: [http://localhost:7803](http://localhost:7803) ### Start Local Supabase Instance To start a local supabase instance (database), run the following command: ```bash bun theme={null} bun sb:start ``` This command will start a local supabase instance on your machine. You can access the supabase instance by visiting the following URL: [http://localhost:8003](http://localhost:8003) You need to have Docker installed and running on your machine to start a local supabase instance. ### Stop Local Supabase Instance To stop the local supabase instance, run the following command: ```bash standard theme={null} bun sb:stop ``` ```bash short-hand theme={null} bun stop ``` ### Better Development Experience In case you want to run all local development servers, run the following command: ```bash bun theme={null} bun devx ``` Running `devx` will: 1. Stop the currently running supabase instance and save current data as backup (if there is any) 2. Install all dependencies 3. Start a new supabase instance (using backed up data) 4. Start all Next.js apps in development mode If you want to have the same procedure without the backup, you can run `bun devrs` instead. This will: 1. Stop the currently running supabase instance (if there is any) 2. Install all dependencies 3. Start a new supabase instance (with clean data from seed.sql) 4. Start all Next.js apps in development mode In case you don't want to run a local supabase instance, you can run `bun dev` instead. ### Local development #### Seed accounts There are 5 seed accounts that are already set up for local development: 1. [local@tuturuuu.com](mailto:local@tuturuuu.com) 2. [user1@tuturuuu.com](mailto:user1@tuturuuu.com) 3. [user2@tuturuuu.com](mailto:user2@tuturuuu.com) 4. [user3@tuturuuu.com](mailto:user3@tuturuuu.com) 5. [user4@tuturuuu.com](mailto:user4@tuturuuu.com) You can use any of these accounts to log in to the app and quickly test the functionality of the app, since they are already set up with the necessary data. #### Authentication A local mail server (**InBucket**) is automatically set up by Supabase to handle authentication emails. You can access the mail server by visiting the following URL: [http://localhost:8004](http://localhost:8004) ## Build To build all apps and packages, run the following command: ```bash bun theme={null} bun run build ``` ## Test To run all tests, run the following command: ```bash bun theme={null} bun run test ``` Tests are still a work in progress. We're currently working on adding tests to all packages to ensure the best quality possible. ## Git Conventions NCTHub uses standardized conventions for Git commits and branch naming. For more information, see the [Git Conventions](/git-conventions) guide to learn how to format your commits and branch names to align with our workflow. # Documenting Source: https://docs.rmitnct.club/documenting Learn how to contribute to our documentation. **Prerequisite**: You should have installed [Node.js](https://nodejs.org) (version 20 or higher) and cloned the [NCTHub Monorepo](https://github.com/rmit-nct/hub) to your local machine. Step 1. Install Mintlify on your local machine: ```bash bun theme={null} bun i -g mintlify ``` ```bash npm theme={null} npm i -g mintlify ``` ```bash yarn theme={null} yarn global add mintlify ``` Step 2. Go to the docs are located (navigate to `apps/docs`) and run the following command: ```bash theme={null} mintlify dev ``` The documentation website is now available at `http://localhost:3000`. Use `cd apps/docs` to navigate to the docs folder. ### Custom Ports Mintlify uses port 3000 by default. You can use the `--port` flag to customize the port Mintlify runs on. For example, use this command to run in port 3333: ```bash theme={null} mintlify dev --port 3333 ``` You will see an error like this if you try to run Mintlify in a port that's already taken: ```md theme={null} Error: listen EADDRINUSE: address already in use :::3000 ``` ## Mintlify Versions Each CLI is linked to a specific version of Mintlify. Please update the CLI if your local website looks different than production. ```bash bun theme={null} bun i -g mintlify@latest ``` ```bash npm theme={null} npm i -g mintlify@latest ``` ```bash yarn theme={null} yarn global add mintlify@latest ``` # Git Conventions Source: https://docs.rmitnct.club/git-conventions Learn how NCTHub uses Conventional Commits and Branch naming to improve development workflow. **Prerequisite**: You should be familiar with basic Git operations and understand the [Monorepo Architecture](/monorepo-architecture) of our codebase. ## Overview NCTHub follows standardized conventions for Git commits and branch naming to improve collaboration, automate releases, and maintain a clean, navigable repository history. We use two main specifications: 1. [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for structured commit messages 2. [Conventional Branch](https://conventional-branch.github.io/) for consistent branch naming These conventions help automate our CI/CD workflows, generate changelogs, and make our development process more efficient. ## Conventional Commits ### What are Conventional Commits? Conventional Commits is a specification for adding human and machine-readable meaning to commit messages. It provides a set of rules for creating an explicit commit history, making it easier to write automated tools on top of. The basic structure of a conventional commit is: ``` [optional scope]: [optional body] [optional footer(s)] ``` ### Types NCTHub uses the following commit types: | Type | Description | Example | | ---------- | ----------------------------------------------- | ------------------------------------------------ | | `feat` | New feature or enhancement | `feat: add dark mode support` | | `fix` | Bug fix | `fix: prevent crash when user data is undefined` | | `docs` | Documentation changes | `docs: update installation instructions` | | `style` | Code style changes (formatting, no code change) | `style: format code with prettier` | | `refactor` | Code refactoring | `refactor: simplify authentication logic` | | `perf` | Performance improvements | `perf: optimize database queries` | | `test` | Add or fix tests | `test: add unit tests for auth middleware` | | `build` | Changes affecting build system or dependencies | `build: update dependency to fix security issue` | | `ci` | Changes to CI configuration files and scripts | `ci: add workflow for staging deployments` | | `chore` | Routine tasks, maintenance | `chore: update package.json metadata` | ### Scopes Scopes provide additional context about which part of the codebase is affected. In our monorepo structure, we often use package or app names as scopes: ``` feat(web): add new dashboard layout fix(ui): correct button alignment in mobile view chore(types): update supabase database types ``` ### Breaking Changes Breaking changes must be indicated by adding a `!` after the type/scope or by using a `BREAKING CHANGE:` footer: ``` feat(api)!: require authentication for all endpoints BREAKING CHANGE: All API endpoints now require authentication tokens. ``` ### Examples Here are some examples of conventional commits used in our codebase: ``` feat(web): add new calendar integration fix(supabase): correct permission issue in auth policy docs(readme): update development setup instructions style: apply consistent formatting with prettier refactor(utils): simplify date formatting functions perf(queries): optimize workspace user loading test(auth): add tests for token verification build(deps): update Next.js to v14 ci(vercel): add automatic preview deployments chore(release): publish packages ``` ## Conventional Branches ### What are Conventional Branches? Conventional Branch refers to a structured naming convention for Git branches that makes it easier to identify branches by type and purpose. The basic structure is: ``` / ``` ### Branch Types NCTHub uses the following branch types: | Type | Description | Example | | --------- | ----------------------- | ------------------------------- | | `main` | Main development branch | `main` | | `feature` | For new features | `feature/user-dashboard` | | `bugfix` | For bug fixes | `bugfix/login-error` | | `hotfix` | For urgent fixes | `hotfix/security-vulnerability` | | `release` | For preparing releases | `release/v1.2.0` | | `chore` | For maintenance tasks | `chore/update-dependencies` | ### Naming Rules 1. Use lowercase alphanumeric characters and hyphens 2. Keep names concise but descriptive 3. Include ticket/issue numbers when applicable 4. Avoid special characters (except hyphens) ### Examples ``` feature/workspace-sharing bugfix/file-upload-error hotfix/auth-vulnerability release/v2.5.0 chore/update-react-18 feature/issue-123-user-profile ``` ## How These Conventions Improve Our Workflow ### 1. Automated Changelog Generation Our conventional commits are used to automatically generate changelogs for releases. Different commit types are categorized accordingly: ```markdown theme={null} # Changelog ## Features - add dark mode support (#123) - add calendar integration (#124) ## Bug Fixes - prevent crash when user data is undefined (#125) ## Documentation - update installation instructions (#126) ``` ### 2. Semantic Versioning Conventional commits help determine the next semantic version for packages: * `fix:` commits trigger a PATCH increment (1.0.0 → 1.0.1) * `feat:` commits trigger a MINOR increment (1.0.0 → 1.1.0) * Commits with `BREAKING CHANGE` trigger a MAJOR increment (1.0.0 → 2.0.0) ### 3. Automated Package Publishing In our CI workflows, package publishing is automatically triggered when a PR with specific commit types is merged. For example, our `release-types-package.yaml` workflow triggers when: ```yaml theme={null} on: pull_request: types: [closed] paths: - 'packages/types/package.json' # ... jobs: check-version-bump: if: github.event.pull_request.merged == true && contains(github.event.pull_request.title, 'chore(@ncthub/types)') # ... ``` ### 4. Better Code Reviews With conventional commits and branches, it's easier to understand the purpose of a pull request at a glance: * A PR from `feature/user-dashboard` with commits like `feat: add user stats widget` clearly indicates a new feature * A PR from `bugfix/auth-issue` with commits like `fix: prevent token expiration error` indicates a bug fix ### 5. Simplifying Navigation Conventional branch names make it easier to navigate the repository history and find specific changes. For example: ```bash theme={null} # Find all feature branches git branch --list "feature/*" # Find branches related to authentication git branch --list "*auth*" ``` ## Tools and Enforcement We use a dedicated CI/CD check to enforce our Git conventions: ### Branch Naming Check We use a GitHub Action workflow to verify that branch names follow our convention: ```yaml theme={null} name: Branch Name Check on: push: branches-ignore: - main - production jobs: check-branch-name: name: Check branch name runs-on: ubuntu-latest steps: - name: Check branch name run: | BRANCH_NAME=${GITHUB_REF#refs/heads/} if ! [[ $BRANCH_NAME =~ ^(feature|bugfix|hotfix|release|chore)/.+ ]]; then echo "❌ Branch name '$BRANCH_NAME' doesn't follow the conventional branch format." echo "Branch name should be in format: type/description" echo "Allowed types: feature, bugfix, hotfix, release, chore" exit 1 else echo "✅ Branch name follows convention: $BRANCH_NAME" fi ``` ## Best Practices ### Writing Good Commit Messages 1. Use the imperative mood ("add" not "added" or "adds") 2. Capitalize the first letter of the description 3. Do not end the description with a period 4. Keep the description under 72 characters 5. Use the body to explain the what and why, not the how Example of a well-formatted commit: ``` feat(auth): Add multi-factor authentication support Implement TOTP-based multi-factor authentication to improve security. The implementation follows the RFC 6238 standard. Closes #123 ``` ### Branch Management 1. Create branches from the latest `main` branch 2. Keep branches focused on a single task or issue 3. Regularly rebase long-lived branches on `main` to avoid merge conflicts 4. Delete branches after they've been merged ### Pull Request Workflow 1. Create a branch with the appropriate type based on the work 2. Make commits using conventional commit messages 3. Push the branch and create a pull request 4. Use conventional commit style for the PR title 5. After approval and merge, delete the branch ## Conclusion Following these Git conventions helps us maintain a clean, understandable repository history, automate release processes, and improve collaboration across the team. By standardizing both commit messages and branch names, we create a more efficient development workflow. For more information, refer to the official documentation for [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) and [Conventional Branch](https://conventional-branch.github.io/). # Introduction Source: https://docs.rmitnct.club/introduction Welcome to the home of NCTHub Documentation. Hero

Powered by Tuturuuu

## Setting up The first step to getting started with NCTHub is to set up your development environment. Learn how to set up your development environment. # Examples Source: https://docs.rmitnct.club/learn/examples/index Practical examples and code samples for the NCT Hub platform This section contains practical examples and code samples demonstrating how to use various components and features of the NCT Hub platform for club management, AI integration, and student development. ## Component Examples ### WorkspaceWrapper Examples showing how to use the WorkspaceWrapper component in different scenarios. The main [WorkspaceWrapper documentation](/platform/components/workspace-wrapper) includes comprehensive code examples demonstrating various usage patterns. ## Usage Patterns ### Server Components ```tsx theme={null} // Basic server component with WorkspaceWrapper export default async function MyPage({ searchParams, }: { searchParams: Promise<{ wsId: string }>; }) { return ( {({ workspace, wsId }) =>
{workspace.name}
}
); } ``` ### Client Components ```tsx theme={null} 'use client'; interface MyComponentProps { workspace: Workspace & { role: WorkspaceUserRole; joined: boolean }; wsId: string; } export function MyComponent({ workspace, wsId }: MyComponentProps) { return
{workspace.name}
; } ``` ### API Routes ```tsx theme={null} // API route with workspace validation export async function GET( request: Request, { params }: { params: Promise<{ wsId: string }> } ) { const { wsId } = await params; const workspace = await getWorkspace(wsId); if (!workspace) { return Response.json({ error: 'Workspace not found' }, { status: 404 }); } return Response.json({ workspace }); } ``` ## Best Practices ### Error Handling ```tsx theme={null} // Proper error handling in components export default async function MyPage({ searchParams }) { return ( }> {({ workspace, wsId }) => { try { return ; } catch (error) { return ; } }} ); } ``` ### Loading States ```tsx theme={null} // Proper loading state handling export default async function MyPage({ searchParams }) { return ( } > {({ workspace, wsId }) => ( }> )} ); } ``` ### Type Safety ```tsx theme={null} // Proper TypeScript usage interface PageProps { searchParams: Promise<{ wsId: string }>; } interface WorkspaceData { workspace: Workspace & { role: WorkspaceUserRole; joined: boolean }; wsId: string; } export default async function MyPage({ searchParams }: PageProps) { return ( {({ workspace, wsId }: WorkspaceData) => ( )} ); } ``` ## Common Patterns ### Dashboard Pages Most dashboard pages follow this pattern: 1. Use WorkspaceWrapper for workspace resolution 2. Fetch additional data based on workspace 3. Render components with proper loading states 4. Handle permissions and access control ### Settings Pages Settings pages typically: 1. Validate user permissions 2. Show different UI based on user role 3. Handle form submissions with proper validation 4. Provide clear feedback to users ### API Endpoints API endpoints should: 1. Validate workspace access 2. Handle errors gracefully 3. Return appropriate HTTP status codes 4. Include proper error messages ## Contributing Examples When adding new examples: 1. Use realistic, practical scenarios 2. Include proper TypeScript types 3. Show error handling 4. Include both server and client examples 5. Update this index page # Learn & Experiment Source: https://docs.rmitnct.club/learn/index Examples, experiments, and learning resources for NCT Hub development and AI integration. Level up your NCT Hub expertise through curated examples, experiments, and learning resources designed for club management, AI integration, and student development. ## Learning Paths * **Examples** – Browse practical snippets and starter code in the [Examples Library](/learn/examples/index). ## NCT Hub Development Flow ```mermaid theme={null} sequenceDiagram participant Student participant NCT Hub participant AI Tools participant Club Community Student->>NCT Hub: Join club activities NCT Hub->>AI Tools: Leverage AI for learning AI Tools->>Student: Enhanced educational experience Student->>Club Community: Share knowledge & projects Club Community-->>NCT Hub: Feed insights back to platform ``` ## Key Learning Areas ### Club Management * Member onboarding and role management * Event planning and coordination * Project tracking and collaboration * Financial management and analytics ### AI Integration * Chat-based assistance for students * Automated content generation * Smart scheduling and notifications * Educational content personalization ### Student Development * Skill-building through hands-on projects * Peer collaboration and mentorship * Real-world project experience * Industry-relevant technology exposure Stay curious—share findings, improve docs, and help us expand what the NCT Hub ecosystem can do. For detailed platform architecture, visit the [Hub section](/platform/index). Need development help? Check out [Development](/development). # Local Supabase Development Source: https://docs.rmitnct.club/local-supabase-development Learn how to work with Supabase locally in the NCT Hub development workflow. **Prerequisite**: You should have installed [Docker](https://www.docker.com/products/docker-desktop/) and followed the [Development](/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: ```bash theme={null} bun sb:start ``` This command launches a local Supabase instance on your machine, accessible at [http://localhost:8003](http://localhost:8003). ### Stopping Supabase To stop the local Supabase instance: ```bash theme={null} bun sb:stop ``` ### Checking Status To view the current URLs and status of your local Supabase instance: ```bash theme={null} bun sb:status ``` ## Development Workflow ### Recommended Startup When developing for NCT Hub, you have several options to start your environment: 1. **Standard Approach**: Start Next.js apps and Supabase separately. ```bash theme={null} bun dev # Starts all Next.js apps bun sb:start # Starts Supabase ``` 2. **Enhanced Development Experience**: Use the `devx` command for a streamlined setup. ```bash theme={null} bun devx ``` 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. ```bash theme={null} bun sb:devrs ``` 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: ```bash theme={null} bun sb:reset ``` 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](http://localhost:8003) 2. Make your changes through the UI 3. Generate a migration file: ```bash theme={null} bun sb:diff ``` 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: ```bash theme={null} bun sb:new ``` 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: ```bash theme={null} bun sb:up ``` 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: ```bash theme={null} bun sb:typegen ``` Alternatively, you can use the shorthand: ```bash theme={null} bun typegen ``` 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: ```typescript theme={null} import type { Database } from '@ncthub/types/supabase'; // Type-safe access to tables const { data, error } = await supabase .from< Database['public']['Tables']['workspace_members']['Row'] >('workspace_members') .select('*') .eq('ws_id', workspaceId); // Type-safe access to specific columns const { data: workspace } = await supabase .from('workspaces') .select('id, name, handle') .eq('id', workspaceId) .single(); // TypeScript knows the structure of 'workspace' with proper types const workspaceName: string = workspace?.name; ``` ### 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: ```typescript theme={null} import type { WorkspaceCourse, WorkspaceRole } from '@ncthub/types/db'; // Use short-hand types directly const { data: roles } = await supabase .from('workspace_roles') .select('*') .eq('ws_id', workspaceId); // Type is now WorkspaceRole[] roles?.forEach((role: WorkspaceRole) => { console.log(role.name, role.permissions); }); // Short-hand types can also include extended properties const course: WorkspaceCourse = { id: 'course-id', ws_id: 'workspace-id', name: 'Course Name', created_at: new Date().toISOString(), updated_at: new Date().toISOString(), href: '/courses/course-id', // Extended property not in the database }; ``` 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](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](mailto:local@tuturuuu.com) 2. [user1@tuturuuu.com](mailto:user1@tuturuuu.com) 3. [user2@tuturuuu.com](mailto:user2@tuturuuu.com) 4. [user3@tuturuuu.com](mailto:user3@tuturuuu.com) 5. [user4@tuturuuu.com](mailto: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](https://supabase.com/docs/guides/local-development/cli/getting-started). ## 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: ```sql theme={null} alter table . enable row level security; ``` ### 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: ```sql theme={null} -- Allow users to select data from their organizations create policy "Users can view data from their organizations" on public.table_name for select to authenticated using ( auth.uid() in ( select user_id from public.workspace_members where workspace_id = table_name.workspace_id ) ); -- Allow organization admins to insert data create policy "Organization admins can insert data" on public.table_name for insert to authenticated with check ( auth.uid() in ( select user_id from public.workspace_members where workspace_id = table_name.workspace_id and role = 'admin' ) ); -- Allow organization admins to update data create policy "Organization admins can update data" on public.table_name for update to authenticated using ( auth.uid() in ( select user_id from public.workspace_members where workspace_id = table_name.workspace_id and role = 'admin' ) ) with check ( auth.uid() in ( select user_id from public.workspace_members where workspace_id = table_name.workspace_id and role = 'admin' ) ); -- Allow organization admins to delete data create policy "Organization admins can delete data" on public.table_name for delete to authenticated using ( auth.uid() in ( select user_id from public.workspace_members where workspace_id = table_name.workspace_id and role = 'admin' ) ); ``` #### Role-based Access For more granular control based on user roles: ```sql theme={null} -- Allow members with specific permission to access a resource create policy "Members with view_projects permission can view projects" on public.projects for select to authenticated using ( exists ( select 1 from public.workspace_member_permissions where user_id = auth.uid() and workspace_id = projects.workspace_id and permission = 'view_projects' ) ); ``` ### Performance Optimization for RLS For better performance in your RLS policies: 1. **Wrap function calls in subqueries**: ```sql theme={null} -- Instead of this using (auth.uid() = user_id); -- Use this using ((select auth.uid()) = user_id); ``` 2. **Use security definer functions** for complex access logic: ```sql theme={null} create or replace function private.can_access_workspace(workspace_uuid uuid) returns boolean language plpgsql security definer as $$ begin return exists ( select 1 from public.workspace_members where user_id = auth.uid() and workspace_id = workspace_uuid ); end; $$; -- Use the function in your policy create policy "Users can access workspace data" on public.table_name for select to authenticated using (private.can_access_workspace(workspace_id)); ``` 3. **Add explicit filters** in your queries even when you have RLS: ```typescript theme={null} // Even though RLS will filter by workspace_id, adding the filter explicitly improves performance const { data } = await supabase .from('projects') .select() .eq('workspace_id', workspaceId); ``` ### 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: ```sql theme={null} -- Test normal user can view their own workspace BEGIN; SET LOCAL ROLE authenticated; -- Mock the auth.uid() function CREATE OR REPLACE FUNCTION auth.uid() RETURNS UUID LANGUAGE SQL AS 'SELECT ''user1-uuid''::UUID'; -- Should return data SELECT is( (SELECT count(*) FROM public.projects WHERE workspace_id = 'workspace1-uuid'), 1, 'User should be able to see their workspace project' ); -- Should return no data SELECT is( (SELECT count(*) FROM public.projects WHERE workspace_id = 'workspace2-uuid'), 0, 'User should not be able to see projects from other workspaces' ); ROLLBACK; ``` ## 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: ```sql theme={null} create or replace function public.handle_new_user() returns trigger language plpgsql security definer as $$ begin -- Create a personal workspace for the new user insert into public.workspaces (id, name, created_by) values (gen_random_uuid(), new.email || '''s workspace', new.id); -- Make the user an admin of their personal workspace insert into public.workspace_members (workspace_id, user_id, role) values ( (select id from public.workspaces where created_by = new.id), new.id, 'admin' ); return new; end; $$; ``` 2. Then, create the trigger: ```sql theme={null} create trigger on_auth_user_created after insert on auth.users for each row execute function public.handle_new_user(); ``` ### Common Triggers in NCT Hub #### Audit Logging ```sql theme={null} create or replace function private.audit_log_changes() returns trigger language plpgsql security definer as $$ begin insert into public.audit_logs ( table_name, record_id, action, old_data, new_data, performed_by ) values ( TG_TABLE_NAME, coalesce(new.id, old.id), TG_OP, case when TG_OP = 'DELETE' or TG_OP = 'UPDATE' then row_to_json(old) else null end, case when TG_OP = 'INSERT' or TG_OP = 'UPDATE' then row_to_json(new) else null end, coalesce(auth.uid(), '00000000-0000-0000-0000-000000000000'::uuid) ); return coalesce(new, old); end; $$; -- Apply this trigger to a table create trigger projects_audit_trigger after insert or update or delete on public.projects for each row execute function private.audit_log_changes(); ``` #### Automated Timestamps ```sql theme={null} create or replace function public.update_timestamp() returns trigger language plpgsql as $$ begin new.updated_at = now(); return new; end; $$; -- Apply to a table create trigger update_projects_timestamp before update on public.projects for each row execute function public.update_timestamp(); ``` ### Testing Triggers You can test triggers by running SQL commands in the local Supabase instance and verifying the results: ```sql theme={null} -- Insert a test user insert into auth.users (id, email) values ('test-uuid', 'test@example.com'); -- Verify the trigger created a workspace select * from public.workspaces where created_by = 'test-uuid'; -- Verify the user is an admin of the workspace select * from public.workspace_members where user_id = 'test-uuid' and role = 'admin'; ``` ## 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: ```sql theme={null} -- Populate auth users INSERT INTO "auth"."users" ( "instance_id", "id", "aud", "role", "email", "encrypted_password", "email_confirmed_at", /* other fields... */ ) VALUES ( '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000001', 'authenticated', 'authenticated', 'local@tuturuuu.com', crypt('password123', gen_salt('bf')), '2023-02-18 23:31:13.017218+00', /* other values... */ ), /* additional users... */ ``` 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: ```sql theme={null} -- Populate workspaces insert into public.workspaces (id, name, handle, creator_id) values ( '00000000-0000-0000-0000-000000000000', 'NCT Hub', 'ncthub', '00000000-0000-0000-0000-000000000001' ), ( '00000000-0000-0000-0000-000000000001', 'Prototype All', 'prototype-all', null ), /* additional workspaces... */ ``` #### 3. Workspace Members and Roles The seed also sets up relationships between users and workspaces with different roles: ```sql theme={null} -- Populate workspace_members insert into public.workspace_members (user_id, ws_id, role) values ( '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000000', 'OWNER' ), ( '00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000000', 'ADMIN' ), ( '00000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000000', 'MEMBER' ), /* additional members... */ ``` #### 4. Workspace Features Configuration The seed file configures workspace features using secrets: ```sql theme={null} -- Populate workspace_secrets insert into public.workspace_secrets (ws_id, name, value) values ( '00000000-0000-0000-0000-000000000000', 'ENABLE_CHAT', 'true' ), ( '00000000-0000-0000-0000-000000000000', 'ENABLE_EDUCATION', 'true' ), /* additional features... */ ``` #### 5. Domain-specific Data The seed includes domain-specific data for different workspace types. For example, healthcare data: ```sql theme={null} -- Populate healthcare_vitals insert into public.healthcare_vitals (id, ws_id, name, unit) values ( '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Nhiệt độ', '°C' ), ( '00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Chiều cao', 'cm' ), /* additional vitals... */ ``` ### 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: ```sql theme={null} -- Create a new user group INSERT INTO public.workspace_user_groups (id, name, ws_id) VALUES ('your-uuid-here', 'New Group', 'workspace-uuid-here') ON CONFLICT (id) DO NOTHING; -- Add a new workspace feature INSERT INTO public.workspace_secrets (ws_id, name, value) VALUES ('workspace-uuid-here', 'ENABLE_NEW_FEATURE', 'true') ON CONFLICT (ws_id, name) DO UPDATE SET value = EXCLUDED.value; ``` ### 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: ```bash theme={null} bun supabase db reset --db-url=postgresql://postgres:postgres@localhost:54322/postgres psql postgresql://postgres:postgres@localhost:54322/postgres -f apps/db/supabase/my_custom_seed.sql ``` ### Exporting Current Data as Seed You can also export your current database data to use as seed data: ```bash theme={null} # Export only data (not schema) to seed.sql bun supabase db dump --db-url=postgresql://postgres:postgres@localhost:54322/postgres --data-only > apps/db/supabase/new_seed.sql ``` This is helpful when you've set up data manually and want to preserve it for future development environments. ### Recommended Seeding Workflow 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: ```typescript theme={null} // 1. Define the schema import { z } from 'zod'; export const flashcardSchema = z.object({ flashcards: z.array( z.object({ front: z.string().describe('Question. Do not use emojis or links.'), back: z.string().describe('Answer. Do not use emojis or links.'), }) ), }); // 2. Setup API endpoint export async function POST(req: Request) { const sbAdmin = await createAdminClient(); const { wsId, context } = await req.json(); // Validate user and workspace permissions const { data: { user }, } = await supabase.auth.getUser(); if (!user) return new Response('Unauthorized', { status: 401 }); // Check workspace feature flag const { count, error } = await sbAdmin .from('workspace_secrets') .select('*', { count: 'exact', head: true }) .eq('ws_id', wsId) .eq('name', 'ENABLE_CHAT') .eq('value', 'true'); if (error) return new Response(error.message, { status: 500 }); if (count === 0) return new Response('You are not allowed to use this feature.', { status: 401, }); // 3. Generate structured data using AI SDK const result = streamObject({ model: google('gemini-2.0-flash-001', { safetySettings: [ // Safety settings configuration... ], }), prompt: `Generate 10 flashcards with the following context: ${context}`, schema: flashcardSchema, }); // 4. Stream the response to the client return result.toTextStreamResponse(); } ``` ### 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: ```typescript theme={null} export const models = [ { value: 'gemini-2.0-flash-001', label: 'gemini-2.0-flash', provider: 'Google', description: 'Gemini 2.0 Flash delivers next-gen features...', context: 1000000, }, // Add other models here... ]; export const defaultModel = models.find( (model) => model.value === 'gemini-2.0-flash-001' && model.provider === 'Google Vertex' ); ``` ### 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: ```typescript theme={null} export const myNewSchema = z.object({ items: z.array( z.object({ name: z.string().describe('Name of the item'), description: z.string().describe('Description of the item'), priority: z.enum(['high', 'medium', 'low']).describe('Priority level'), }) ), }); ``` ### 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: ```sql theme={null} -- Enable AI chat features for a workspace INSERT INTO public.workspace_secrets (ws_id, name, value) VALUES ('your-workspace-id', 'ENABLE_CHAT', 'true'); -- Enable AI document features for a workspace INSERT INTO public.workspace_secrets (ws_id, name, value) VALUES ('your-workspace-id', 'ENABLE_DOCS', 'true'); ``` ### 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: ``` GOOGLE_GENERATIVE_AI_API_KEY=your-api-key ``` 2. Verify the workspace has the necessary feature flags enabled in your local database ```sql theme={null} SELECT * FROM workspace_secrets WHERE ws_id = 'your-workspace-id' AND name = 'ENABLE_CHAT'; ``` 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: ```typescript theme={null} try { // AI SDK code here } catch (error: any) { console.log(error); return NextResponse.json( { message: `## Edge API Failure\nCould not complete the request. Please view the **Stack trace** below.\n\`\`\`bash\n${error?.stack}`, }, { status: 200, } ); } ``` # Monorepo Architecture Source: https://docs.rmitnct.club/monorepo-architecture Understanding NCT Hub monorepo architecture and the benefits of using Turborepo. **Prerequisite**: You should have followed the [Development](/development) setup guide to understand the basic structure of the codebase. ## What is a Monorepo? A monorepo is a single repository containing multiple distinct projects with well-defined relationships. This approach differs from a polyrepo strategy where each project has its own separate repository. > "A monorepo is a single repository containing multiple distinct projects, with well-defined relationships." > — [monorepo.tools](https://monorepo.tools/) It's important to note that a monorepo is not the same as a monolith. A monolith is a single, tightly coupled application, while a monorepo can contain many independent applications, libraries, and tools that can be deployed separately. ## Why NCT Hub Uses a Monorepo NCT Hub's platform is built as a monorepo (`@rmit-nct/hub`) for several key reasons: ### 1. Code Sharing Without Overhead Our monorepo structure makes it easy to share code across different applications and services without the overhead of publishing packages. Core components, utilities, and business logic can be shared across multiple applications without duplicating code. ``` platform/ ├── apps/ │ ├── web/ # Main web application │ ├── docs/ # Documentation site (Mintlify) │ └── ... # Other applications └── packages/ ├── ai/ # Shared AI functions & configurations ├── ui/ # Shared UI components ├── types/ # Shared TypeScript types ├── utils/ # Shared utilities ├── supabase/ # Supabase client and utilities └── ... # Other shared packages ``` ### 2. Atomic Changes Across Projects When making changes that affect multiple parts of the platform, we can make those changes in a single commit. This ensures that all parts of the system remain compatible with each other, reducing integration issues. For example, when updating a database schema: 1. We can update the Supabase schema in `apps/db/supabase/migrations` 2. Update the TypeScript types in `packages/types/src/supabase.ts` 3. Update all affected applications in the same pull request ### 3. Consistent Developer Experience A monorepo allows us to standardize tooling, testing, and deployment processes across all projects. This creates a consistent development experience regardless of which part of the platform a developer is working on. All developers use the same: * Package manager (bun) * Build system (Turborepo) * Code style guidelines (enforced by ESLint and Prettier) * Testing framework * CI/CD pipelines ### 4. Simplified Dependency Management Managing dependencies in a monorepo is simpler because we can ensure all projects use the same versions of shared dependencies, avoiding version conflicts. ## Why We Chose Turborepo NCT Hub uses [Turborepo](https://turborepo.org/) as its build system for several reasons: ### 1. Incremental Builds with Caching Turborepo provides intelligent caching of build artifacts. This means that if a file hasn't changed, Turborepo will use the cached result instead of rebuilding it, significantly reducing build times. ```bash theme={null} # Only builds what changed since the last build bun run build ``` ### 2. Parallel Task Execution Turborepo automatically parallelizes tasks, maximizing the use of available CPU cores. ```bash theme={null} # Runs lint across all packages in parallel bun lint ``` ### 3. Task Orchestration Turborepo understands dependencies between packages and ensures tasks are run in the correct order. ```bash theme={null} # In turbo.json { "pipeline": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**", ".next/**"] } } } ``` ### 4. Remote Caching For CI/CD pipelines, Turborepo supports remote caching, which means build artifacts can be shared across different environments. ## Monorepo Structure Our monorepo is organized into several main directories: ### apps/ Contains all deployable applications. Each application is a standalone project that can be deployed independently. ``` apps/ ├── web/ # Main web application ├── docs/ # Documentation site (Mintlify) └── db/ # Database migrations and scripts ``` ### packages/ Contains shared libraries and utilities that are used by multiple applications. ``` packages/ ├── ui/ # Shared UI components ├── types/ # Shared TypeScript types including Supabase types ├── utils/ # Shared utilities ├── ai/ # AI-related utilities └── supabase/ # Supabase client and utilities ``` ## Development Workflow When working in our monorepo, you'll typically: 1. Clone the repository: `git clone https://github.com/rmit-nct/hub.git` 2. Install dependencies: `bun install` 3. Start the development servers: `bun dev` or `bun devx` (with Supabase) For more detailed instructions on development workflow, see the [Development](/development) and [Local Supabase Development](/local-supabase-development) guides. ## Best Practices When working in our monorepo, follow these best practices: ### 1. Keep Projects Modular Even though all code lives in one repository, maintain clear boundaries between projects. Each package or app should have a well-defined purpose and API. ### 2. Use Workspace References When one project depends on another within the monorepo, use workspace references: ```json theme={null} { "dependencies": { "@ncthub/ui": "workspace:*", "@ncthub/types": "workspace:*" } } ``` ### 3. Think About Build Order Be mindful of dependencies between packages. If package B depends on package A, ensure that changes to package A trigger rebuilds of package B. ### 4. Use Correct Scope for Changes * For changes that affect a single application, focus your changes there * For changes that affect multiple applications, consider extracting common code to a shared package * For global changes (like tooling updates), ensure you test across all affected projects ## Common Challenges and Solutions ### Challenge: Long Build Times **Solution:** Turborepo's caching mechanism helps, but also: * Be selective about what you build during development * Use `bun --filter` to focus on specific packages ```bash theme={null} # Only build the web app and its dependencies bun --filter web... build ``` ### Challenge: Dependency Management **Solution:** * Regularly update dependencies * Bun automatically detects workspace packages from the root `package.json` workspaces field * Consider using `bun dedupe` to eliminate duplicate dependencies ### Challenge: CI/CD Pipeline Complexity **Solution:** * Use GitHub Actions workflows that are specific to the affected parts of the codebase * Leverage Turborepo's `--filter` and `--since` flags to only build what's changed ## Further Resources * [monorepo.tools](https://monorepo.tools/): Comprehensive information about monorepos * [Turborepo Documentation](https://turbo.build/repo/docs): Official Turborepo documentation * [Bun Workspace](https://bun.sh/docs/install/workspaces): How bun handles monorepos # Neo Chess Source: https://docs.rmitnct.club/platform/applications/neo-chess Multiplayer chess game with AI opponents and real-time gameplay Neo Chess is NCT Hub's multiplayer chess game featuring real-time gameplay, AI opponents, and competitive features designed to engage club members in strategic thinking and friendly competition. ## Overview Neo Chess provides an interactive chess experience that combines traditional chess gameplay with modern web technologies, real-time synchronization, and AI-powered opponents for solo play. ## Key Features ### **Multiplayer Gameplay** * **Real-time Matches** – Play against other club members with live move synchronization * **Matchmaking System** – Find opponents based on skill level and availability * **Spectator Mode** – Watch ongoing matches between other players * **Game History** – Track your matches and performance over time ### **AI Opponents** * **Multiple Difficulty Levels** – Choose from beginner to expert AI opponents * **Adaptive AI** – AI opponents that adjust to your playing style * **Training Mode** – Practice against AI without affecting your rating * **Puzzle Challenges** – Solve chess puzzles and tactical problems ### **Competitive Features** * **Rating System** – Track your chess rating and improvement * **Leaderboards** – See top players in the club * **Tournaments** – Participate in club chess tournaments * **Achievements** – Unlock badges for various accomplishments ### **Visual Design** * **Custom Chess Pieces** – Beautiful, detailed chess piece designs * **Dark/Light Themes** – Choose your preferred board theme * **Animations** – Smooth piece movements and transitions * **Responsive Design** – Play on desktop, tablet, or mobile devices ## Technical Implementation ### Game Architecture ```mermaid theme={null} flowchart TB subgraph "Client Side" Board["Chess Board UI"] Pieces["Chess Pieces"] Moves["Move Validation"] UI["Game Interface"] end subgraph "Real-time Sync" Supabase["Supabase Realtime"] WebSocket["WebSocket Connection"] end subgraph "AI Engine" ChessJS["Chess.js Engine"] AI["AI Opponent Logic"] Minimax["Minimax Algorithm"] end subgraph "Database" Games["Game States"] Users["Player Data"] Stats["Statistics"] end Board --> Moves Moves --> Supabase Supabase --> WebSocket WebSocket --> Board AI --> ChessJS ChessJS --> Minimax Minimax --> AI Supabase --> Games Games --> Users Users --> Stats ``` ### Chess Piece Assets The game uses custom-designed chess pieces stored in the public folder: #### White Pieces * `w_king.png` - White King * `w_queen.png` - White Queen * `w_rook.png` - White Rook * `w_bishop.png` - White Bishop * `w_knight.png` - White Knight * `w_pawn.png` - White Pawn #### Black Pieces * `b_king.png` - Black King * `b_queen.png` - Black Queen * `b_rook.png` - Black Rook * `b_bishop.png` - Black Bishop * `b_knight.png` - Black Knight * `b_pawn.png` - Black Pawn ### Real-time Synchronization ```typescript theme={null} // Real-time game state updates const channel = supabase .channel(`chess-game-${gameId}`) .on( 'postgres_changes', { event: 'UPDATE', schema: 'public', table: 'chess_games', filter: `id=eq.${gameId}`, }, (payload) => { updateGameState(payload.new); } ) .subscribe(); ``` ### AI Implementation ```typescript theme={null} // AI move generation using minimax algorithm function getBestMove(game: Chess, depth: number): string { const moves = game.moves(); let bestMove = ''; let bestScore = -Infinity; for (const move of moves) { game.move(move); const score = minimax(game, depth - 1, false); game.undo(); if (score > bestScore) { bestScore = score; bestMove = move; } } return bestMove; } ``` ## Game Modes ### **Quick Match** * **Random Opponent** – Get matched with an available player * **Time Controls** – Choose from blitz, rapid, or classical time controls * **Rating Range** – Play against opponents of similar skill level ### **AI Practice** * **Difficulty Selection** – Choose from 5 difficulty levels * **Analysis Mode** – Get hints and move suggestions * **Puzzle Training** – Solve tactical puzzles and endgames ### **Club Tournaments** * **Scheduled Events** – Participate in club-organized tournaments * **Swiss System** – Fair tournament pairing system * **Prizes** – Compete for club recognition and achievements ### **Analysis Mode** * **Game Review** – Analyze your completed games * **Move Evaluation** – See computer evaluation of moves * **Learning Resources** – Access chess tutorials and guides ## User Interface ### Game Board * **Drag & Drop** – Intuitive piece movement * **Legal Move Highlighting** – Visual indicators for valid moves * **Move History** – Track all moves in algebraic notation * **Position Evaluation** – Real-time position assessment ### Game Controls * **Timer Display** – Show remaining time for both players * **Move Indicators** – Visual feedback for piece movements * **Game Status** – Current game state and phase * **Chat System** – Communicate with opponent (optional) ### Settings Panel * **Theme Selection** – Choose board and piece colors * **Sound Controls** – Enable/disable move sounds * **Animation Speed** – Adjust piece movement speed * **Difficulty Settings** – For AI opponents ## Database Schema ### Chess Games Table ```sql theme={null} CREATE TABLE chess_games ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), white_player_id UUID REFERENCES users(id), black_player_id UUID REFERENCES users(id), game_state JSONB NOT NULL, moves TEXT[] DEFAULT '{}', status TEXT DEFAULT 'active', time_control JSONB, created_at TIMESTAMP DEFAULT NOW(), updated_at TIMESTAMP DEFAULT NOW() ); ``` ### Player Statistics Table ```sql theme={null} CREATE TABLE chess_player_stats ( user_id UUID PRIMARY KEY REFERENCES users(id), rating INTEGER DEFAULT 1200, games_played INTEGER DEFAULT 0, games_won INTEGER DEFAULT 0, games_lost INTEGER DEFAULT 0, games_drawn INTEGER DEFAULT 0, best_rating INTEGER DEFAULT 1200, last_played TIMESTAMP, created_at TIMESTAMP DEFAULT NOW() ); ``` ## API Endpoints ### Game Management ```typescript theme={null} // Create new game POST /api/chess/games { "opponentId": "uuid", "timeControl": "blitz|rapid|classical", "color": "white|black|random" } // Make move POST /api/chess/games/{gameId}/move { "move": "e2e4", "timestamp": "2025-01-10T10:00:00Z" } // Get game state GET /api/chess/games/{gameId} ``` ### Player Statistics ```typescript theme={null} // Get player stats GET /api/chess/stats/{userId} // Get leaderboard GET /api/chess/leaderboard?limit=10&timeframe=monthly ``` ## Integration with NCT Hub ### Member System * **Automatic Registration** – All NCT Hub members can play * **Profile Integration** – Chess stats appear in member profiles * **Achievement System** – Chess achievements integrate with club badges ### Club Events * **Tournament Organization** – Club admins can organize chess tournaments * **Event Integration** – Chess tournaments appear in club calendar * **Member Engagement** – Track member participation in chess activities ### Analytics * **Game Statistics** – Track club-wide chess engagement * **Popular Time Slots** – Identify peak playing times * **Member Retention** – Monitor chess player activity over time ## Future Enhancements ### Planned Features * **Video Analysis** – Record and analyze games * **Opening Explorer** – Database of chess openings * **Endgame Trainer** – Practice endgame scenarios * **Mobile App** – Native mobile application * **Streaming Integration** – Stream games to club members ### Community Features * **Chess Clubs** – Form sub-groups within NCT Hub * **Mentorship Program** – Pair experienced players with beginners * **Chess Lessons** – Structured learning program * **Problem Solving** – Daily chess puzzles and challenges ## Related Resources * [Platform Overview](/platform/index) – Understanding the complete platform architecture * [Member Management](/platform/features/user-management) – Managing club members and roles * [Analytics Dashboard](/platform/features/command-center-dashboard) – Tracking game analytics and engagement * [Neo Crush](/platform/applications/neo-crush) – Another NCT Hub game application # Neo Crush Source: https://docs.rmitnct.club/platform/applications/neo-crush Multiplayer puzzle game with real-time competition and colorful gameplay Neo Crush is NCT Hub's multiplayer puzzle game featuring colorful gems, strategic gameplay, and real-time competition. Players match gems to clear the board while competing against other club members in fast-paced, engaging rounds. ## Overview Neo Crush combines the addictive gameplay of match-3 puzzle games with multiplayer competition, creating an engaging social gaming experience that brings NCT Hub members together through friendly competition and collaborative play. ## Key Features ### **Multiplayer Gameplay** * **Real-time Competition** – Play against other club members simultaneously * **Live Leaderboards** – See rankings update in real-time during matches * **Tournament Mode** – Participate in organized competitions * **Spectator Support** – Watch other players' games in progress ### **Colorful Gem System** * **Seven Gem Types** – Each with unique colors and properties: * **Red** - Classic fire gems * **Orange** - Energetic citrus gems * **Yellow** - Bright sun gems * **Green** - Natural forest gems * **Blue** - Cool ocean gems * **Purple** - Mystical royal gems * **Pink** - Sweet candy gems ### **Competitive Features** * **Score Tracking** – Monitor your performance and improvement * **Achievement System** – Unlock badges for various accomplishments * **Seasonal Rankings** – Compete in monthly leaderboards * **Club Championships** – Participate in NCT Hub tournaments ### **Game Mechanics** * **Match-3 Gameplay** – Classic puzzle mechanics with modern twists * **Power-ups** – Special gems that create explosive effects * **Combo System** – Chain matches for massive point multipliers * **Time Pressure** – Strategic gameplay under time constraints ## Technical Implementation ### Game Architecture ```mermaid theme={null} flowchart TB subgraph "Client Side" Grid["Game Grid UI"] Gems["Gem Rendering"] Physics["Match Detection"] Score["Score System"] end subgraph "Real-time Sync" Supabase["Supabase Realtime"] WebSocket["WebSocket Connection"] Leaderboard["Live Leaderboard"] end subgraph "Game Logic" Engine["Game Engine"] Matches["Match Detection"] Combos["Combo System"] Effects["Visual Effects"] end subgraph "Database" Games["Game Sessions"] Scores["Player Scores"] Stats["Statistics"] Achievements["Achievements"] end Grid --> Gems Gems --> Physics Physics --> Score Score --> Supabase Supabase --> WebSocket WebSocket --> Leaderboard Leaderboard --> Grid Engine --> Matches Matches --> Combos Combos --> Effects Supabase --> Games Games --> Scores Scores --> Stats Stats --> Achievements ``` ### Gem Asset System The game uses high-quality gem assets stored in the public folder: #### Gem Colors * `red.png` - Vibrant red fire gems * `orange.png` - Bright orange citrus gems * `yellow.png` - Glowing yellow sun gems * `green.png` - Rich green forest gems * `blue.png` - Deep blue ocean gems * `purple.png` - Royal purple gems * `pink.png` - Sweet pink candy gems ### Real-time Synchronization ```typescript theme={null} // Real-time score updates and leaderboard const gameChannel = supabase .channel(`neo-crush-game-${gameId}`) .on( 'postgres_changes', { event: 'INSERT', schema: 'public', table: 'game_scores', }, (payload) => { updateLeaderboard(payload.new); } ) .on( 'postgres_changes', { event: 'UPDATE', schema: 'public', table: 'neo_crush_games', filter: `id=eq.${gameId}`, }, (payload) => { updateGameState(payload.new); } ) .subscribe(); ``` ### Match Detection Algorithm ```typescript theme={null} // Detect matches in the game grid function findMatches(grid: Gem[][], minLength: number = 3): Match[] { const matches: Match[] = []; // Check horizontal matches for (let row = 0; row < grid.length; row++) { for (let col = 0; col < grid[row].length - minLength + 1; col++) { const color = grid[row][col].color; let matchLength = 1; while ( col + matchLength < grid[row].length && grid[row][col + matchLength].color === color ) { matchLength++; } if (matchLength >= minLength) { matches.push({ type: 'horizontal', row, startCol: col, length: matchLength, color, }); } } } // Check vertical matches (similar logic) // ... return matches; } ``` ## Game Modes ### **Quick Play** * **Solo Practice** – Play against yourself to improve skills * **Daily Challenges** – Special puzzles with unique objectives * **Tutorial Mode** – Learn game mechanics and strategies * **Free Play** – Unlimited gameplay without competition ### **Multiplayer Modes** * **Real-time Battles** – Compete against other players simultaneously * **Turn-based Matches** – Take turns in strategic gameplay * **Team Competitions** – Work together with other club members * **Club Tournaments** – Organized competitions with prizes ### **Competitive Play** * **Ranked Matches** – Earn rating points through competitive play * **Seasonal Leagues** – Compete in monthly ranking systems * **Achievement Hunts** – Complete specific challenges for rewards * **Speed Rounds** – Fast-paced matches with time pressure ### **Learning Modes** * **Strategy Guide** – Learn advanced techniques and combos * **Pattern Recognition** – Practice identifying match opportunities * **Combo Training** – Master chain reactions and multipliers * **Power-up Tutorials** – Understand special gem effects ## User Interface ### Game Grid * **Drag & Drop** – Intuitive gem swapping mechanics * **Visual Feedback** – Highlighted valid moves and potential matches * **Smooth Animations** – Polished gem movements and effects * **Grid Indicators** – Show possible match locations ### Score Display * **Current Score** – Real-time point tracking * **Multiplier Display** – Show current combo multiplier * **High Score** – Personal best and club records * **Progress Bar** – Visual representation of game progress ### Leaderboard * **Live Updates** – Real-time ranking changes * **Player Avatars** – Visual identification of competitors * **Score Tracking** – Current round scores and total points * **Club Rankings** – NCT Hub member standings ### Game Controls * **Pause/Resume** – Control game flow * **Settings Panel** – Adjust graphics and audio * **Help System** – Access tutorials and tips * **Social Features** – Chat and emoji reactions ## Database Schema ### Game Sessions Table ```sql theme={null} CREATE TABLE neo_crush_games ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), game_type TEXT NOT NULL, -- 'quick_play', 'multiplayer', 'tournament' status TEXT DEFAULT 'active', -- 'active', 'completed', 'paused' max_players INTEGER DEFAULT 1, time_limit INTEGER, -- seconds created_at TIMESTAMP DEFAULT NOW(), ended_at TIMESTAMP ); ``` ### Player Scores Table ```sql theme={null} CREATE TABLE neo_crush_scores ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), game_id UUID REFERENCES neo_crush_games(id), user_id UUID REFERENCES users(id), score INTEGER NOT NULL, gems_matched INTEGER DEFAULT 0, combos_created INTEGER DEFAULT 0, power_ups_used INTEGER DEFAULT 0, rank INTEGER, created_at TIMESTAMP DEFAULT NOW() ); ``` ### Player Statistics Table ```sql theme={null} CREATE TABLE neo_crush_player_stats ( user_id UUID PRIMARY KEY REFERENCES users(id), total_games INTEGER DEFAULT 0, total_score BIGINT DEFAULT 0, high_score INTEGER DEFAULT 0, average_score INTEGER DEFAULT 0, gems_matched BIGINT DEFAULT 0, combos_created INTEGER DEFAULT 0, win_streak INTEGER DEFAULT 0, best_win_streak INTEGER DEFAULT 0, rating INTEGER DEFAULT 1000, last_played TIMESTAMP, created_at TIMESTAMP DEFAULT NOW() ); ``` ## API Endpoints ### Game Management ```typescript theme={null} // Create new game POST /api/neo-crush/games { "gameType": "multiplayer|quick_play|tournament", "maxPlayers": 4, "timeLimit": 300 } // Submit score POST /api/neo-crush/games/{gameId}/score { "score": 1250, "gemsMatched": 45, "combosCreated": 3, "powerUpsUsed": 1 } // Get leaderboard GET /api/neo-crush/leaderboard?timeframe=daily|weekly|monthly&limit=50 ``` ### Player Statistics ```typescript theme={null} // Get player stats GET /api/neo-crush/stats/{userId} // Get game history GET /api/neo-crush/games/history/{userId}?limit=20 // Update achievement progress POST /api/neo-crush/achievements/progress { "achievementId": "uuid", "progress": 75 } ``` ## Game Mechanics ### Scoring System * **Base Points** – Points for each gem matched * **Combo Multipliers** – Increasing multipliers for chain reactions * **Power-up Bonuses** – Extra points for special gem effects * **Time Bonuses** – Additional points for quick matches * **Perfect Games** – Bonus points for no-miss rounds ### Power-up System * **Bomb Gems** – Clear surrounding gems in explosion * **Lightning Gems** – Destroy entire rows or columns * **Rainbow Gems** – Match any color gem * **Time Extensions** – Add extra seconds to the timer * **Score Multipliers** – Temporarily increase point values ### Combo Mechanics * **Chain Reactions** – Cascading matches from falling gems * **Multiplier Progression** – Increasing multipliers for longer chains * **Special Combinations** – Unique patterns for massive scores * **Power-up Synergy** – Combining power-ups for maximum effect ## Integration with NCT Hub ### Member Engagement * **Daily Challenges** – Encourage regular club member participation * **Social Features** – Share achievements and high scores * **Club Events** – Organize NCT Hub gaming tournaments * **Member Recognition** – Highlight top performers ### Analytics Integration * **Engagement Metrics** – Track member participation in gaming * **Performance Analytics** – Monitor game statistics and trends * **Social Interaction** – Measure community engagement through gaming * **Retention Tracking** – Monitor long-term member activity ### Achievement System * **Club Badges** – Special achievements for NCT Hub members * **Skill Progression** – Track improvement over time * **Community Goals** – Collaborative achievements for the entire club * **Event Participation** – Recognition for tournament participation ## Future Enhancements ### Planned Features * **Mobile Optimization** – Enhanced touch controls for mobile devices * **Voice Chat** – Real-time communication during multiplayer matches * **Custom Themes** – NCT Hub branded gem designs and backgrounds * **AI Opponents** – Practice against computer-controlled players ### Community Features * **Guild System** – Form gaming teams within NCT Hub * **Mentorship Program** – Experienced players help newcomers * **Streaming Integration** – Broadcast matches to club members * **Cross-platform Play** – Play across different devices ### Advanced Gameplay * **Puzzle Mode** – Solve predetermined gem arrangements * **Boss Battles** – Special challenging rounds with unique mechanics * **Seasonal Events** – Limited-time content and special rewards * **Custom Levels** – User-generated content and challenges ## Related Resources * [Platform Overview](/platform/index) – Understanding the complete platform architecture * [Member Management](/platform/features/user-management) – Managing club members and roles * [Analytics Dashboard](/platform/features/command-center-dashboard) – Tracking game analytics and engagement * [Neo Chess](/platform/applications/neo-chess) – Another NCT Hub game application # API Route Patterns Source: https://docs.rmitnct.club/platform/architecture/api-routes Implementing and organizing API routes in the NCT Hub platform The NCT Hub platform uses Next.js App Router API routes with consistent patterns for versioning, authentication, error handling, and workspace isolation. The API is designed to support both club management operations and external integrations. ## Route Organization ### Directory Structure ``` apps/web/src/app/api/ ├── v1/ # Versioned public API │ ├── aurora/ # Aurora AI system endpoints │ ├── calendar/ # Calendar integration │ ├── infrastructure/ # Infrastructure management │ ├── users/ # User management │ └── workspaces/ # Workspace operations ├── ai/ # AI-specific endpoints │ ├── chat/ # Multi-provider chat (Anthropic, OpenAI, Google) │ └── objects/ # AI object generation (flashcards, quizzes) ├── auth/ # Authentication endpoints │ ├── callback/ # OAuth callbacks │ ├── me/ # Current user info │ ├── otp/ # One-time passwords │ └── logout/ # Session management ├── meet-together/ # Event scheduling │ └── plans/ # Meet Together plans ├── students/ # Student management ├── users/ # User operations ├── workspaces/ # Workspace management └── [wsId]/ # Workspace-scoped endpoints ├── crawlers/ # Data crawling ├── datasets/ # AI datasets ├── finance/ # Financial tracking ├── members/ # Member management └── tasks/ # Task management ``` ## Versioned Public API ### Pattern: `/api/v1/*` Use for public-facing APIs that external clients consume. ```typescript theme={null} // app/api/v1/workspaces/route.ts import { createClient } from '@ncthub/supabase/server'; import { NextRequest, NextResponse } from 'next/server'; import { z } from 'zod'; // GET /api/v1/workspaces export async function GET(request: NextRequest) { try { const supabase = createClient(); // Check authentication const { data: { user }, } = await supabase.auth.getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } // Fetch user's workspaces const { data: workspaces, error } = await supabase .from('workspace_members') .select( ` ws_id, role, workspaces ( id, name, logo_url ) ` ) .eq('user_id', user.id) .eq('pending', false); if (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } return NextResponse.json({ data: workspaces?.map((w) => w.workspaces), }); } catch (error) { return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } } // POST /api/v1/workspaces const createWorkspaceSchema = z.object({ name: z.string().min(1).max(100), logo_url: z.string().url().optional(), }); export async function POST(request: NextRequest) { try { const supabase = createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } // Validate request body const body = await request.json(); const parsed = createWorkspaceSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( { error: 'Invalid input', details: parsed.error.issues }, { status: 400 } ); } // Create workspace const { data: workspace, error } = await supabase .from('workspaces') .insert({ name: parsed.data.name, logo_url: parsed.data.logo_url, }) .select() .single(); if (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } // Add creator as owner await supabase.from('workspace_members').insert({ ws_id: workspace.id, user_id: user.id, role: 'owner', }); return NextResponse.json({ data: workspace }, { status: 201 }); } catch (error) { return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } } ``` ## Workspace-Scoped API ### Pattern: `/api/[wsId]/*` Use for workspace-specific operations with automatic workspace context. ```typescript theme={null} // app/api/[wsId]/tasks/route.ts import { hasPermission } from '@/lib/permissions'; import { createClient } from '@ncthub/supabase/server'; import { NextRequest, NextResponse } from 'next/server'; import { z } from 'zod'; // GET /api/[wsId]/tasks export async function GET( request: NextRequest, { params }: { params: { wsId: string } } ) { try { const supabase = createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } // Check workspace membership const isMember = await isWorkspaceMember(user.id, params.wsId); if (!isMember) { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); } // Parse query parameters const searchParams = request.nextUrl.searchParams; const listId = searchParams.get('listId'); const completed = searchParams.get('completed'); // Build query let query = supabase .from('workspace_tasks') .select('*') .eq('ws_id', params.wsId); if (listId) query = query.eq('list_id', listId); if (completed !== null) query = query.eq('completed', completed === 'true'); const { data: tasks, error } = await query; if (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } return NextResponse.json({ data: tasks }); } catch (error) { return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } } // POST /api/[wsId]/tasks const createTaskSchema = z.object({ name: z.string().min(1).max(255), description: z.string().optional(), listId: z.string(), priority: z.number().int().min(0).max(5).optional(), dueDate: z.string().datetime().optional(), }); export async function POST( request: NextRequest, { params }: { params: { wsId: string } } ) { try { const supabase = createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } // Check permission const canCreate = await hasPermission(user.id, params.wsId, 'manage_tasks'); if (!canCreate) { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); } // Validate input const body = await request.json(); const parsed = createTaskSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( { error: 'Invalid input', details: parsed.error.issues }, { status: 400 } ); } // Create task const { data: task, error } = await supabase .from('workspace_tasks') .insert({ ws_id: params.wsId, name: parsed.data.name, description: parsed.data.description, list_id: parsed.data.listId, priority: parsed.data.priority, due_date: parsed.data.dueDate, created_by: user.id, }) .select() .single(); if (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } return NextResponse.json({ data: task }, { status: 201 }); } catch (error) { return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } } // DELETE /api/[wsId]/tasks/[taskId] export async function DELETE( request: NextRequest, { params }: { params: { wsId: string; taskId: string } } ) { try { const supabase = createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const canDelete = await hasPermission(user.id, params.wsId, 'manage_tasks'); if (!canDelete) { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); } const { error } = await supabase .from('workspace_tasks') .delete() .eq('id', params.taskId) .eq('ws_id', params.wsId); // Ensure workspace isolation if (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } return NextResponse.json({ success: true }); } catch (error) { return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } } ``` ## AI Endpoints ### Pattern: `/api/ai/*` Use for AI-specific operations with model selection and token tracking. ```typescript theme={null} // app/api/ai/chat/route.ts import { createGoogleGenerativeAI } from '@ai-sdk/google'; import { createClient } from '@ncthub/supabase/server'; import { streamText } from 'ai'; import { NextRequest } from 'next/server'; import { z } from 'zod'; export const runtime = 'edge'; export const maxDuration = 60; const chatRequestSchema = z.object({ messages: z.array( z.object({ role: z.enum(['user', 'assistant', 'system']), content: z.string(), }) ), model: z.string().optional(), }); export async function POST(request: NextRequest) { try { const supabase = createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) { return new Response('Unauthorized', { status: 401 }); } // Validate input const body = await request.json(); const parsed = chatRequestSchema.safeParse(body); if (!parsed.success) { return new Response('Invalid input', { status: 400 }); } // Check AI feature flag const { data: workspace } = await supabase .from('workspace_secrets') .select('value') .eq('ws_id', body.wsId) .eq('name', 'ENABLE_AI') .single(); if (workspace?.value !== 'true') { return new Response('AI not enabled for workspace', { status: 403 }); } const google = createGoogleGenerativeAI({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY, }); const model = parsed.data.model || 'gemini-2.0-flash-exp'; const result = streamText({ model: google(model), messages: parsed.data.messages, onFinish: async ({ usage }) => { // Track token usage await supabase.from('workspace_ai_executions').insert({ ws_id: body.wsId, model, input_tokens: usage.promptTokens, output_tokens: usage.completionTokens, total_cost: calculateCost(model, usage), }); }, }); return result.toDataStreamResponse(); } catch (error) { console.error('AI chat error:', error); return new Response('Internal server error', { status: 500 }); } } function calculateCost( model: string, usage: { promptTokens: number; completionTokens: number } ): number { // Pricing per million tokens const pricing: Record = { 'gemini-2.0-flash-exp': { input: 0, output: 0 }, // Free tier 'gemini-2.0-pro-exp': { input: 0, output: 0 }, // Free tier }; const price = pricing[model] || { input: 0, output: 0 }; return ( (usage.promptTokens / 1_000_000) * price.input + (usage.completionTokens / 1_000_000) * price.output ); } ``` ## Authentication Endpoints ### Pattern: `/api/auth/*` Use edge runtime for auth endpoints. ```typescript theme={null} // app/api/auth/otp/route.ts import { createClient } from '@ncthub/supabase/server'; import { NextRequest, NextResponse } from 'next/server'; import { z } from 'zod'; export const runtime = 'edge'; const otpRequestSchema = z.object({ email: z.string().email(), }); export async function POST(request: NextRequest) { try { const supabase = createClient(); const body = await request.json(); const parsed = otpRequestSchema.safeParse(body); if (!parsed.success) { return NextResponse.json({ error: 'Invalid email' }, { status: 400 }); } const { error } = await supabase.auth.signInWithOtp({ email: parsed.data.email, options: { emailRedirectTo: `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback`, }, }); if (error) { return NextResponse.json({ error: error.message }, { status: 400 }); } return NextResponse.json({ success: true }); } catch (error) { return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } } ``` ## Error Response Standards ### Standard Error Format ```typescript theme={null} interface ErrorResponse { error: string; details?: any; code?: string; } ``` ### HTTP Status Codes * `200` - Success * `201` - Created * `204` - No Content * `400` - Bad Request (validation errors) * `401` - Unauthorized (not authenticated) * `403` - Forbidden (not authorized) * `404` - Not Found * `409` - Conflict * `422` - Unprocessable Entity * `429` - Too Many Requests * `500` - Internal Server Error ### Error Handling Pattern ```typescript theme={null} export async function POST(request: NextRequest) { try { // Implementation } catch (error) { console.error('API error:', error); if (error instanceof z.ZodError) { return NextResponse.json( { error: 'Validation failed', details: error.errors }, { status: 400 } ); } return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } } ``` ## Middleware Pattern ### Permission Middleware ```typescript theme={null} // lib/api/middleware.ts import { hasPermission } from '@/lib/permissions'; import { createClient } from '@ncthub/supabase/server'; import { NextRequest, NextResponse } from 'next/server'; type Handler = ( req: NextRequest, context: { params: any; user: any } ) => Promise; export function withAuth(handler: Handler) { return async (req: NextRequest, context: any) => { const supabase = createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } return handler(req, { ...context, user }); }; } export function withPermission(permission: string, handler: Handler) { return withAuth(async (req, context) => { const wsId = context.params.wsId; const allowed = await hasPermission(context.user.id, wsId, permission); if (!allowed) { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); } return handler(req, context); }); } ``` ### Usage ```typescript theme={null} // app/api/[wsId]/tasks/route.ts import { withPermission } from '@/lib/api/middleware'; export const POST = withPermission( 'manage_tasks', async (req, { params, user }) => { // Implementation with guaranteed permission } ); ``` ## CORS Configuration ```typescript theme={null} // app/api/v1/workspaces/route.ts export async function OPTIONS(request: NextRequest) { return new NextResponse(null, { status: 200, headers: { 'Access-Control-Allow-Origin': process.env.ALLOWED_ORIGIN || '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', }, }); } ``` ## Rate Limiting ```typescript theme={null} import { Ratelimit } from '@upstash/ratelimit'; import { Redis } from '@upstash/redis'; const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, '10 s'), // 10 requests per 10 seconds }); export async function POST(request: NextRequest) { const identifier = request.headers.get('x-forwarded-for') || 'anonymous'; const { success } = await ratelimit.limit(identifier); if (!success) { return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 }); } // Continue with request } ``` ## Best Practices ### ✅ DO 1. **Always validate input** ```typescript theme={null} const parsed = schema.safeParse(body); if (!parsed.success) return error(400); ``` 2. **Check authentication first** ```typescript theme={null} const { data: { user } } = await supabase.auth.getUser(); if (!user) return error(401); ``` 3. **Verify workspace permissions** ```typescript theme={null} const allowed = await hasPermission(user.id, wsId, 'manage_tasks'); if (!allowed) return error(403); ``` 4. **Use edge runtime for auth** ```typescript theme={null} export const runtime = 'edge'; ``` 5. **Set max duration for long operations** ```typescript theme={null} export const maxDuration = 60; // seconds ``` ### ❌ DON'T 1. **Don't expose sensitive errors** ```typescript theme={null} // ❌ Bad return NextResponse.json({ error: error.stack }); ``` 2. **Don't skip workspace isolation** ```typescript theme={null} // ❌ Bad: Can access any workspace .delete().eq('id', taskId) // ✅ Good: Workspace-scoped .delete().eq('id', taskId).eq('ws_id', wsId) ``` 3. **Don't use user client for mutations** ```typescript theme={null} // ❌ Bad: Bypasses RLS const supabase = createAdminClient(); ``` ## Related Documentation * [Authentication](/platform/architecture/authentication) * [Authorization](/platform/architecture/authorization) * [tRPC](/platform/architecture/trpc) * [Data Fetching](/platform/architecture/data-fetching) # Authentication Patterns Source: https://docs.rmitnct.club/platform/architecture/authentication Authentication implementation patterns in the NCT Hub platform The NCT Hub platform uses Supabase Auth for user authentication with support for email/password, OAuth providers, one-time passwords (OTP), and session management. The system is designed to handle club member authentication, external integrations, and secure API access. ## Authentication Flow ``` ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ Client │──1──>│ Supabase │──2──>│ Database │ │ (Browser/App)│ │ Auth │ │ (RLS) │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ │ │<─────────3───────────│ │ │ Session Token │ │ │ │ │ │──────4──────────────────────────────────────>│ │ Authenticated Request (w/ session) │ │<─────────────────────────────────────────────│ │ Data (filtered by RLS) │ ``` 1. User signs in via Supabase Auth 2. Supabase validates credentials against database 3. Client receives session token 4. Subsequent requests include session token for RLS ## Sign Up ### Basic Email/Password Sign Up ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/next/server'; import { redirect } from 'next/navigation'; export async function signUp(formData: FormData) { const supabase = await createClient(); const email = formData.get('email') as string; const password = formData.get('password') as string; const displayName = formData.get('displayName') as string; const { data, error } = await supabase.auth.signUp({ email, password, options: { data: { display_name: displayName, }, emailRedirectTo: `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback`, }, }); if (error) { return { error: error.message }; } redirect('/onboarding'); } ``` ### Client Component ```tsx theme={null} 'use client'; import { signUp } from './actions'; import { useState } from 'react'; export function SignUpForm() { const [error, setError] = useState(null); async function handleSubmit(formData: FormData) { const result = await signUp(formData); if (result?.error) { setError(result.error); } } return (
{error &&

{error}

}
); } ``` ## Sign In ### Email/Password Sign In ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; import { redirect } from 'next/navigation'; export async function signIn(formData: FormData) { const supabase = createClient(); const email = formData.get('email') as string; const password = formData.get('password') as string; const { data, error } = await supabase.auth.signInWithPassword({ email, password, }); if (error) { return { error: error.message }; } redirect('/dashboard'); } ``` ### OAuth Sign In ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function signInWithOAuth(provider: 'google' | 'github') { const supabase = createClient(); const { data, error } = await supabase.auth.signInWithOAuth({ provider, options: { redirectTo: `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback`, }, }); if (error) { return { error: error.message }; } return { url: data.url }; } ``` Client Component: ```tsx theme={null} 'use client'; import { signInWithOAuth } from './actions'; export function OAuthButtons() { async function handleOAuthSignIn(provider: 'google' | 'github') { const result = await signInWithOAuth(provider); if (result.url) { window.location.href = result.url; } } return (
); } ``` ## Sign Out ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; import { redirect } from 'next/navigation'; export async function signOut() { const supabase = createClient(); await supabase.auth.signOut(); redirect('/login'); } ``` ## Multi-Factor Authentication (MFA) ### Enable TOTP MFA ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function enableMFA() { const supabase = createClient(); // Enroll in MFA const { data, error } = await supabase.auth.mfa.enroll({ factorType: 'totp', }); if (error) throw error; return { qrCode: data.totp.qr_code, // Display to user secret: data.totp.secret, // For manual entry factorId: data.id, }; } ``` ### Verify MFA Enrollment ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function verifyMFAEnrollment(factorId: string, code: string) { const supabase = createClient(); const { data, error } = await supabase.auth.mfa.challengeAndVerify({ factorId, code, }); if (error) throw error; return { success: true }; } ``` ### MFA Challenge During Sign In ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function signInWithMFA(email: string, password: string) { const supabase = createClient(); // Initial sign in const { data: signInData, error: signInError } = await supabase.auth.signInWithPassword({ email, password, }); if (signInError) throw signInError; // Check if MFA is required const { data: factors } = await supabase.auth.mfa.listFactors(); if (factors && factors.totp.length > 0) { const factorId = factors.totp[0].id; // Create MFA challenge const { data: challengeData, error: challengeError } = await supabase.auth.mfa.challenge({ factorId }); if (challengeError) throw challengeError; return { requiresMFA: true, challengeId: challengeData.id, factorId, }; } return { requiresMFA: false }; } ``` ### Verify MFA Code ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function verifyMFACode( factorId: string, challengeId: string, code: string ) { const supabase = createClient(); const { data, error } = await supabase.auth.mfa.verify({ factorId, challengeId, code, }); if (error) throw error; return { success: true }; } ``` ## Session Management ### Get Current Session ```typescript theme={null} import { createClient } from '@ncthub/supabase/server'; export async function getSession() { const supabase = createClient(); const { data: { session }, error, } = await supabase.auth.getSession(); if (error) throw error; return session; } ``` ### Get Current User ```typescript theme={null} import { createClient } from '@ncthub/supabase/server'; export async function getCurrentUser() { const supabase = createClient(); const { data: { user }, error, } = await supabase.auth.getUser(); if (error || !user) { return null; } return user; } ``` ### Refresh Session ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function refreshSession() { const supabase = createClient(); const { data, error } = await supabase.auth.refreshSession(); if (error) throw error; return data.session; } ``` ## Password Reset ### Request Password Reset ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function requestPasswordReset(email: string) { const supabase = createClient(); const { error } = await supabase.auth.resetPasswordForEmail(email, { redirectTo: `${process.env.NEXT_PUBLIC_APP_URL}/auth/reset-password`, }); if (error) throw error; return { success: true }; } ``` ### Reset Password ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function resetPassword(newPassword: string) { const supabase = createClient(); const { data, error } = await supabase.auth.updateUser({ password: newPassword, }); if (error) throw error; return { success: true }; } ``` ## Email Verification ### Resend Verification Email ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function resendVerificationEmail() { const supabase = createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user?.email) { throw new Error('No user email found'); } const { error } = await supabase.auth.resend({ type: 'signup', email: user.email, }); if (error) throw error; return { success: true }; } ``` ## Cross-App Authentication The platform supports token-based authentication across different apps using `@ncthub/auth/cross-app`. ### Generate Cross-App Token ```typescript theme={null} import { generateCrossAppToken } from '@ncthub/auth/cross-app'; export async function createShortenerLink(userId: string) { // Generate token that shortener app can verify const token = await generateCrossAppToken(userId, { expiresIn: '1h', app: 'shortener', }); return { url: `${process.env.SHORTENER_APP_URL}/create?token=${token}`, }; } ``` ### Verify Cross-App Token ```typescript theme={null} import { verifyCrossAppToken } from '@ncthub/auth/cross-app'; export async function handleCrossAppRequest(token: string) { const payload = await verifyCrossAppToken(token); if (!payload) { throw new Error('Invalid token'); } // payload contains: { userId, app, exp, iat } return payload; } ``` ## Middleware Authentication Protect routes using Next.js middleware: ```typescript theme={null} // middleware.ts import { createDynamicClient } from '@ncthub/supabase/server'; import { NextRequest, NextResponse } from 'next/server'; export async function proxy(request: NextRequest) { const supabase = createDynamicClient(); const { data: { user }, } = await supabase.auth.getUser(); // Protect dashboard routes if (request.nextUrl.pathname.startsWith('/dashboard') && !user) { return NextResponse.redirect(new URL('/login', request.url)); } // Redirect authenticated users from auth pages if (request.nextUrl.pathname.startsWith('/login') && user) { return NextResponse.redirect(new URL('/dashboard', request.url)); } return NextResponse.next(); } export const config = { matcher: ['/dashboard/:path*', '/login', '/signup'], }; ``` ## Protected Server Component ```typescript theme={null} import { createClient } from '@ncthub/supabase/server'; import { redirect } from 'next/navigation'; export default async function ProtectedPage() { const supabase = createClient(); const { data: { user } } = await supabase.auth.getUser(); if (!user) { redirect('/login'); } return (

Welcome, {user.email}

); } ``` ## Client-Side Authentication ### useUser Hook ```tsx theme={null} 'use client'; import type { User } from '@supabase/supabase-js'; import { createClient } from '@ncthub/supabase/next/client'; import { useEffect, useState } from 'react'; export function useUser() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const supabase = createClient(); useEffect(() => { // Get initial session supabase.auth.getSession().then(({ data: { session } }) => { setUser(session?.user ?? null); setLoading(false); }); // Listen for auth changes const { data: { subscription }, } = supabase.auth.onAuthStateChange((_event, session) => { setUser(session?.user ?? null); }); return () => subscription.unsubscribe(); }, []); return { user, loading }; } ``` ### Usage ```tsx theme={null} 'use client'; import { useUser } from '@/hooks/useUser'; export function UserProfile() { const { user, loading } = useUser(); if (loading) return
Loading...
; if (!user) return
Not authenticated
; return
Logged in as {user.email}
; } ``` ## Identity Linking Link multiple auth providers to same account: ```typescript theme={null} 'use server'; import { createClient } from '@ncthub/supabase/server'; export async function linkIdentity(provider: 'google' | 'github') { const supabase = createClient(); const { data, error } = await supabase.auth.linkIdentity({ provider, }); if (error) throw error; return { url: data.url }; } ``` ## Best Practices ### ✅ DO 1. **Always check authentication server-side** ```typescript theme={null} const { data: { user }, } = await supabase.auth.getUser(); if (!user) throw new Error('Unauthorized'); ``` 2. **Use edge runtime for auth routes** ```typescript theme={null} // app/api/auth/otp/route.ts export const runtime = 'edge'; ``` 3. **Redirect after authentication** ```typescript theme={null} redirect('/dashboard'); // Don't return sensitive data ``` 4. **Handle errors gracefully** ```typescript theme={null} if (error) return { error: error.message }; ``` 5. **Implement MFA for sensitive operations** ```typescript theme={null} const mfaRequired = await checkMFAEnabled(userId); ``` ### ❌ DON'T 1. **Don't trust client-side auth state alone** ```typescript theme={null} // ❌ Bad if (localStorage.getItem('user')) { /* ... */ } ``` 2. **Don't expose sensitive data in auth redirects** ```typescript theme={null} // ❌ Bad redirect(`/dashboard?apiKey=${apiKey}`); ``` 3. **Don't store passwords** ```typescript theme={null} // ❌ Bad: Let Supabase handle password storage ``` 4. **Don't use `createAdminClient()` for auth operations** ```typescript theme={null} // ❌ Bad: Use regular client const supabase = createAdminClient(); await supabase.auth.signUp({ ... }); ``` ## Related Documentation * [Authorization](/platform/architecture/authorization) - Permission system * [Supabase Client](/reference/packages/supabase) - Client creation patterns * [RLS Policies](/reference/database/rls-policies) - Database security ## External Resources * [Supabase Auth Documentation](https://supabase.com/docs/guides/auth) * [Next.js Authentication](https://nextjs.org/docs/authentication) # Authorization & Permissions Source: https://docs.rmitnct.club/platform/architecture/authorization Permission system and authorization patterns in the NCT Hub platform The NCT Hub platform implements a sophisticated role-based access control (RBAC) system with granular workspace-scoped permissions designed for club management, member roles, and department-specific access control. ## Permission Architecture ``` ┌─────────────────────────────────────────────────────────┐ │ Workspace │ │ ┌────────────────────────────────────────────────────┐ │ │ │ Workspace Member (User + Role) │ │ │ │ ┌──────────────────────────────────────────────┐ │ │ │ │ │ Role Permissions │ │ │ │ │ │ ├─ manage_workspace_settings │ │ │ │ │ │ ├─ manage_users │ │ │ │ │ │ ├─ manage_finance │ │ │ │ │ │ └─ ... │ │ │ │ │ └──────────────────────────────────────────────┘ │ │ │ └────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────┘ ``` ## Permission System ### Available Permissions The platform defines 30+ workspace permissions organized into groups: #### Infrastructure * `manage_infrastructure_settings` - Manage infrastructure-level settings #### Workspace * `manage_workspace_settings` - Manage workspace configuration * `manage_workspace_security` - Manage security settings #### Users * `manage_users` - Create, update, delete users * `manage_user_groups` - Manage user groups and tags * `manage_user_roles` - Assign and modify user roles * `view_disabled_users` - View disabled user accounts * `disable_user` - Disable/enable user accounts #### Finance * `manage_finance` - Manage financial resources * `ai_lab_assistant` - Access AI lab features #### Calendar * `manage_calendar` - Manage calendar events * `manage_external_users` - Manage external/guest users #### Content * `manage_documents` - Manage document resources #### Inventory * `manage_inventory` - Manage inventory resources ### Permission Groups Defined in `@ncthub/utils/permissions`: ```typescript theme={null} export const permissionGroups = { INFRASTRUCTURE: ['manage_infrastructure_settings'], WORKSPACE: ['manage_workspace_settings', 'manage_workspace_security'], USERS: [ 'manage_users', 'manage_user_groups', 'manage_user_roles', 'view_disabled_users', 'disable_user', ], FINANCE: ['manage_finance', 'ai_lab_assistant'], CALENDAR: ['manage_calendar', 'manage_external_users'], DOCUMENTS: ['manage_documents'], INVENTORY: ['manage_inventory'], }; ``` ## Database Schema ### `workspace_role_permissions` ```sql theme={null} CREATE TABLE workspace_role_permissions ( ws_id text REFERENCES workspaces(id) ON DELETE CASCADE, role_id text NOT NULL, permission workspace_role_permission NOT NULL, created_at timestamptz DEFAULT now(), PRIMARY KEY (ws_id, role_id, permission) ); ``` ### `workspace_members` ```sql theme={null} CREATE TABLE workspace_members ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), ws_id text REFERENCES workspaces(id) ON DELETE CASCADE, user_id uuid REFERENCES workspace_users(id) ON DELETE CASCADE, role text NOT NULL, pending boolean DEFAULT false, created_at timestamptz DEFAULT now() ); ``` ## Checking Permissions ### Server-Side Permission Check ```typescript theme={null} import { createClient } from '@ncthub/supabase/server'; import type { Database } from '@ncthub/types'; type Permission = Database['public']['Enums']['workspace_role_permission']; export async function hasPermission( userId: string, wsId: string, permission: Permission ): Promise { const supabase = createClient(); const { data, error } = await supabase .from('workspace_members') .select( ` role, workspace_role_permissions!inner ( permission ) ` ) .eq('user_id', userId) .eq('ws_id', wsId) .eq('workspace_role_permissions.permission', permission) .limit(1); if (error) return false; return (data?.length || 0) > 0; } ``` ### Usage in Server Actions ```typescript theme={null} 'use server'; import { hasPermission } from '@/lib/permissions'; import { createClient } from '@ncthub/supabase/server'; import { redirect } from 'next/navigation'; export async function deleteUser(wsId: string, userId: string) { const supabase = createClient(); // Get current user const { data: { user: currentUser }, } = await supabase.auth.getUser(); if (!currentUser) { throw new Error('Unauthorized'); } // Check permission const canManageUsers = await hasPermission( currentUser.id, wsId, 'manage_users' ); if (!canManageUsers) { throw new Error('Forbidden: You do not have permission to manage users'); } // Perform operation const { error } = await supabase .from('workspace_members') .delete() .eq('user_id', userId) .eq('ws_id', wsId); if (error) throw error; redirect(`/${wsId}/users`); } ``` ### Usage in API Routes ```typescript theme={null} // app/api/[wsId]/users/route.ts import { hasPermission } from '@/lib/permissions'; import { createClient } from '@ncthub/supabase/server'; import { NextRequest, NextResponse } from 'next/server'; export async function DELETE( request: NextRequest, { params }: { params: { wsId: string } } ) { const supabase = createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const canManageUsers = await hasPermission( user.id, params.wsId, 'manage_users' ); if (!canManageUsers) { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); } const body = await request.json(); const { error } = await supabase .from('workspace_members') .delete() .eq('user_id', body.userId) .eq('ws_id', params.wsId); if (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } return NextResponse.json({ success: true }); } ``` ### Check Multiple Permissions ```typescript theme={null} export async function hasAnyPermission( userId: string, wsId: string, permissions: Permission[] ): Promise { const supabase = createClient(); const { data, error } = await supabase .from('workspace_members') .select( ` role, workspace_role_permissions!inner ( permission ) ` ) .eq('user_id', userId) .eq('ws_id', wsId) .in('workspace_role_permissions.permission', permissions) .limit(1); if (error) return false; return (data?.length || 0) > 0; } ``` ```typescript theme={null} export async function hasAllPermissions( userId: string, wsId: string, permissions: Permission[] ): Promise { const results = await Promise.all( permissions.map((p) => hasPermission(userId, wsId, p)) ); return results.every((result) => result === true); } ``` ## Permission Utilities ### Get User Permissions ```typescript theme={null} import { createClient } from '@ncthub/supabase/server'; export async function getUserPermissions( userId: string, wsId: string ): Promise { const supabase = createClient(); const { data, error } = await supabase .from('workspace_members') .select( ` role, workspace_role_permissions ( permission ) ` ) .eq('user_id', userId) .eq('ws_id', wsId) .single(); if (error || !data) return []; return data.workspace_role_permissions.map((p) => p.permission); } ``` ### Get User Role ```typescript theme={null} import { createClient } from '@ncthub/supabase/server'; export async function getUserRole( userId: string, wsId: string ): Promise { const supabase = createClient(); const { data, error } = await supabase .from('workspace_members') .select('role') .eq('user_id', userId) .eq('ws_id', wsId) .single(); if (error || !data) return null; return data.role; } ``` ## Assigning Permissions ### Create Role with Permissions ```typescript theme={null} 'use server'; import { hasPermission } from '@/lib/permissions'; import { createClient } from '@ncthub/supabase/server'; export async function createRole( wsId: string, roleId: string, permissions: string[] ) { const supabase = createClient(); // Check if user can manage roles const { data: { user }, } = await supabase.auth.getUser(); if (!user) throw new Error('Unauthorized'); const canManageRoles = await hasPermission( user.id, wsId, 'manage_user_roles' ); if (!canManageRoles) { throw new Error('Forbidden'); } // Insert permissions const permissionRows = permissions.map((permission) => ({ ws_id: wsId, role_id: roleId, permission, })); const { error } = await supabase .from('workspace_role_permissions') .insert(permissionRows); if (error) throw error; return { success: true }; } ``` ### Assign Role to User ```typescript theme={null} 'use server'; import { hasPermission } from '@/lib/permissions'; import { createClient } from '@ncthub/supabase/server'; export async function assignRole(wsId: string, userId: string, roleId: string) { const supabase = createClient(); const { data: { user: currentUser }, } = await supabase.auth.getUser(); if (!currentUser) throw new Error('Unauthorized'); const canManageRoles = await hasPermission( currentUser.id, wsId, 'manage_user_roles' ); if (!canManageRoles) { throw new Error('Forbidden'); } const { error } = await supabase .from('workspace_members') .update({ role: roleId }) .eq('user_id', userId) .eq('ws_id', wsId); if (error) throw error; return { success: true }; } ``` ## Client-Side Permission Checks ### usePermissions Hook ```tsx theme={null} 'use client'; import { getUserPermissions } from '@/lib/permissions'; import { useEffect, useState } from 'react'; export function usePermissions(wsId: string, userId: string) { const [permissions, setPermissions] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { getUserPermissions(userId, wsId) .then(setPermissions) .finally(() => setLoading(false)); }, [wsId, userId]); const hasPermission = (permission: string) => permissions.includes(permission); return { permissions, hasPermission, loading }; } ``` ### Usage ```tsx theme={null} 'use client'; import { usePermissions } from '@/hooks/usePermissions'; import { useUser } from '@/hooks/useUser'; export function UserManagementPanel({ wsId }: { wsId: string }) { const { user } = useUser(); const { hasPermission, loading } = usePermissions(wsId, user?.id || ''); if (loading) return
Loading...
; const canManageUsers = hasPermission('manage_users'); const canManageRoles = hasPermission('manage_user_roles'); return (
{canManageUsers && } {canManageRoles && } {!canManageUsers && !canManageRoles && (

You do not have permission to manage users

)}
); } ``` ### Conditional Rendering ```tsx theme={null} 'use client'; import { usePermissions } from '@/hooks/usePermissions'; export function PermissionGate({ wsId, userId, permission, children, fallback = null, }: { wsId: string; userId: string; permission: string; children: React.ReactNode; fallback?: React.ReactNode; }) { const { hasPermission, loading } = usePermissions(wsId, userId); if (loading) return fallback; if (!hasPermission(permission)) return fallback; return <>{children}; } ``` Usage: ```tsx theme={null} Access denied

} >
``` ## Common Permission Patterns ### Admin Check ```typescript theme={null} export async function isWorkspaceAdmin( userId: string, wsId: string ): Promise { return hasPermission(userId, wsId, 'manage_infrastructure_settings'); } ``` ### Owner Check ```typescript theme={null} import { createClient } from '@ncthub/supabase/server'; export async function isWorkspaceOwner( userId: string, wsId: string ): Promise { const supabase = createClient(); const { data, error } = await supabase .from('workspace_members') .select('role') .eq('user_id', userId) .eq('ws_id', wsId) .eq('role', 'owner') .limit(1); if (error) return false; return (data?.length || 0) > 0; } ``` ### Member Check ```typescript theme={null} import { createClient } from '@ncthub/supabase/server'; export async function isWorkspaceMember( userId: string, wsId: string ): Promise { const supabase = createClient(); const { data, error } = await supabase .from('workspace_members') .select('id') .eq('user_id', userId) .eq('ws_id', wsId) .eq('pending', false) .limit(1); if (error) return false; return (data?.length || 0) > 0; } ``` ## Permission Middleware Create reusable permission middleware for API routes: ```typescript theme={null} // lib/middleware/permissions.ts import { hasPermission } from '@/lib/permissions'; import { createClient } from '@ncthub/supabase/server'; import { NextRequest, NextResponse } from 'next/server'; export function withPermission( permission: string, handler: (req: NextRequest, context: any) => Promise ) { return async (req: NextRequest, context: any) => { const supabase = createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const wsId = context.params.wsId; const allowed = await hasPermission(user.id, wsId, permission); if (!allowed) { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); } return handler(req, context); }; } ``` Usage: ```typescript theme={null} // app/api/[wsId]/users/route.ts import { withPermission } from '@/lib/middleware/permissions'; export const DELETE = withPermission( 'manage_users', async (req, { params }) => { // Implementation return NextResponse.json({ success: true }); } ); ``` ## Best Practices ### ✅ DO 1. **Always check permissions server-side** ```typescript theme={null} const allowed = await hasPermission(userId, wsId, 'manage_users'); if (!allowed) throw new Error('Forbidden'); ``` 2. **Use granular permissions** ```typescript theme={null} // ✅ Good: Specific permission hasPermission(userId, wsId, 'manage_finance'); // ❌ Bad: Too broad hasPermission(userId, wsId, 'admin'); ``` 3. **Check permissions before operations** ```typescript theme={null} // Check first if (!(await hasPermission(userId, wsId, 'manage_users'))) { throw new Error('Forbidden'); } // Then perform operation await deleteUser(userId); ``` 4. **Return appropriate HTTP status codes** ```typescript theme={null} if (!user) return 401; // Unauthorized if (!hasPermission) return 403; // Forbidden ``` 5. **Cache permission checks when appropriate** ```typescript theme={null} const permissions = await getUserPermissions(userId, wsId); const canManageUsers = permissions.includes('manage_users'); const canManageRoles = permissions.includes('manage_user_roles'); ``` ### ❌ DON'T 1. **Don't rely only on client-side permission checks** ```typescript theme={null} // ❌ Bad: Client can bypass this if (!hasPermission) return; ``` 2. **Don't expose permission logic in URLs** ```typescript theme={null} // ❌ Bad /api/admin/delete-user?isAdmin=true ``` 3. **Don't hard-code permission checks** ```typescript theme={null} // ❌ Bad if (user.role === 'admin') { ... } // ✅ Good if (await hasPermission(userId, wsId, 'manage_users')) { ... } ``` 4. **Don't skip permission checks for "trusted" operations** ```typescript theme={null} // ❌ Bad: Always check permissions async function internalDeleteUser(userId: string) { await supabase.from('users').delete().eq('id', userId); } ``` ## Related Documentation * [Authentication](/platform/architecture/authentication) - User authentication * [RLS Policies](/reference/database/rls-policies) - Database-level security * [Supabase Client](/reference/packages/supabase) - Client usage patterns ## External Resources * [Row-Level Security](https://supabase.com/docs/guides/auth/row-level-security) * [RBAC Patterns](https://www.osohq.com/academy/role-based-access-control-rbac) # Data Fetching Strategies Source: https://docs.rmitnct.club/platform/architecture/data-fetching When and how to fetch data using RSC, Server Actions, React Query, and tRPC in NCT Hub The NCT Hub platform uses a layered approach to data fetching, choosing the right strategy based on use case, caching requirements, and user experience needs. This ensures optimal performance for club management operations, real-time features, and member interactions. ## Strategy Preference Order Choose the earliest applicable strategy: 1. **Pure Server Component (RSC)** - Read-only, cacheable, SEO-critical data 2. **Server Action** - Mutations returning updated state to RSC 3. **RSC + Client Hydration** - When background refresh needed 4. **React Query (Client-Side)** - Interactive, rapidly changing state 5. **Realtime Subscriptions** - Live updates materially improve UX ## 1. Pure Server Component (RSC) ### When to Use ✅ **Best For:** * Initial page load data * SEO-critical content * Rarely changing data * Read-only operations * Database queries that don't need real-time updates ❌ **Not For:** * Interactive forms * Frequent updates * Client-side state * Real-time data ### Implementation ```typescript theme={null} // app/[locale]/(dashboard)/[wsId]/tasks/page.tsx import { createClient } from '@ncthub/supabase/next/server'; export default async function TasksPage({ params, }: { params: { wsId: string }; }) { const supabase = await createClient(); // Direct database query in Server Component const { data: tasks } = await supabase .from('workspace_tasks') .select('*') .eq('ws_id', params.wsId) .order('created_at', { ascending: false }) .limit(20); return (

Tasks

); } ``` ### Caching Strategy ```typescript theme={null} // app/[locale]/(dashboard)/[wsId]/tasks/page.tsx // Revalidate every hour export const revalidate = 3600; // OR generate static params export async function generateStaticParams() { const supabase = createClient(); const { data: workspaces } = await supabase.from('workspaces').select('id'); return workspaces?.map((ws) => ({ wsId: ws.id })) || []; } ``` ### Loading States ```typescript theme={null} // app/[locale]/(dashboard)/[wsId]/tasks/loading.tsx export default function Loading() { return ; } ``` ### Error Handling ```typescript theme={null} // app/[locale]/(dashboard)/[wsId]/tasks/error.tsx 'use client'; export default function Error({ error, reset, }: { error: Error; reset: () => void; }) { return (

Something went wrong!

); } ``` ## 2. Server Actions ### When to Use ✅ **Best For:** * Form submissions * Mutations with server-side validation * Operations requiring auth checks * Redirects after mutations * Progressive enhancement ❌ **Not For:** * Read operations (use RSC instead) * Complex client-side state management * Real-time updates ### Implementation ```typescript theme={null} // app/[locale]/(dashboard)/[wsId]/tasks/actions.ts 'use server'; import { createClient } from '@ncthub/supabase/server'; import { revalidatePath } from 'next/cache'; import { redirect } from 'next/navigation'; import { z } from 'zod'; const createTaskSchema = z.object({ name: z.string().min(1).max(255), description: z.string().optional(), listId: z.string(), }); export async function createTask(formData: FormData) { const supabase = createClient(); // Check authentication const { data: { user }, } = await supabase.auth.getUser(); if (!user) { throw new Error('Unauthorized'); } // Validate input const parsed = createTaskSchema.safeParse({ name: formData.get('name'), description: formData.get('description'), listId: formData.get('listId'), }); if (!parsed.success) { return { error: 'Invalid input' }; } // Perform mutation const { data, error } = await supabase .from('workspace_tasks') .insert({ name: parsed.data.name, description: parsed.data.description, list_id: parsed.data.listId, created_by: user.id, }) .select() .single(); if (error) { return { error: error.message }; } // Revalidate cache revalidatePath(`/[locale]/(dashboard)/[wsId]/tasks`); return { success: true, task: data }; } export async function deleteTask(taskId: string, wsId: string) { const supabase = createClient(); const { error } = await supabase .from('workspace_tasks') .delete() .eq('id', taskId); if (error) { return { error: error.message }; } revalidatePath(`/[locale]/(dashboard)/${wsId}/tasks`); redirect(`/${wsId}/tasks`); } ``` ### Client Usage ```tsx theme={null} 'use client'; import { createTask } from './actions'; import { useFormStatus } from 'react-dom'; function SubmitButton() { const { pending } = useFormStatus(); return ( ); } export function CreateTaskForm({ listId }: { listId: string }) { async function handleSubmit(formData: FormData) { const result = await createTask(formData); if (result.error) { console.error(result.error); } } return (