### Environment Variables Setup (Bash) Source: https://github.com/yosrend/mahwa2006/blob/main/README.md Shell command to copy the example environment file to a local file, which will then be populated with specific API keys and URLs for Clerk and Supabase. This is crucial for application configuration. ```bash cp .env.example .env.local ``` -------------------------------- ### Environment Configuration for Services Source: https://context7.com/yosrend/mahwa2006/llms.txt This bash script outlines the necessary environment variables for configuring authentication (Clerk), database (Supabase), and AI services (OpenAI, Anthropic). It details where to obtain the keys and provides setup steps, including copying the example file, creating applications/projects, and running migrations. ```bash # Clerk Authentication (required for auth) # Get from: https://dashboard.clerk.com NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_xxxxxxxxxxxxxxxxxxxxx CLERK_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxx # Supabase Database (required for database operations) # Get from: https://supabase.com/dashboard/project/_/settings/api NEXT_PUBLIC_SUPABASE_URL=https://your-project-id.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... # OpenAI API (optional, for AI chat) # Get from: https://platform.openai.com/api-keys OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxxxxxxx # Anthropic API (optional, alternative AI provider) # Get from: https://console.anthropic.com/settings/keys ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxx # Setup steps: # 1. Copy .env.example to .env.local # cp .env.example .env.local # 2. Create Clerk application # - Go to https://dashboard.clerk.com # - Create new application # - Copy publishable and secret keys # - Enable email/password authentication # 3. Create Supabase project # - Go to https://supabase.com/dashboard # - Create new project # - Go to Settings → API # - Copy URL and anon key # - Configure third-party auth for Clerk (see SUPABASE_CLERK_SETUP.md) # 4. Get OpenAI API key (optional) # - Go to https://platform.openai.com/api-keys # - Create new API key # - Add billing method # 5. Run migrations # supabase db push # 6. Start development server # npm run dev # Verify setup by checking: # - Authentication: Sign in/out works # - Database: RLS policies applied correctly # - AI Chat: Streaming responses work (if API key added) ``` -------------------------------- ### Clone Repository and Install Dependencies (Bash) Source: https://github.com/yosrend/mahwa2006/blob/main/README.md Commands to clone the starter kit repository and install project dependencies using npm, yarn, or pnpm. Ensures all necessary packages are available for development. ```bash git clone cd codeguide-starter-kit npm install # or yarn install # or pnpm install ``` -------------------------------- ### Start Development Server (Bash) Source: https://github.com/yosrend/mahwa2006/blob/main/README.md Commands to start the Next.js development server using npm, yarn, or pnpm. This command initiates the local development environment, allowing you to preview the application at http://localhost:3000. ```bash npm run dev # or yarn dev # or pnpm dev ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/yosrend/mahwa2006/blob/main/SUPABASE_CLERK_SETUP.md Example of environment variables required for Clerk and Supabase integration in a Next.js application, including publishable keys, secret keys, and Supabase URLs/keys. ```bash # Clerk Authentication NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_... CLERK_SECRET_KEY=sk_test_... # Supabase NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ... ``` -------------------------------- ### Development Commands for Project Workflow Source: https://github.com/yosrend/mahwa2006/blob/main/CLAUDE.md Provides essential npm commands for managing the development workflow of the project. These include starting the development server, building for production, starting the production server, and running ESLint for code quality checks. ```bash npm run dev # Start development server with Turbopack npm run build # Build for production npm run start # Start production server npm run lint # Run ESLint ``` -------------------------------- ### Supabase Client Initialization Source: https://github.com/yosrend/mahwa2006/blob/main/SUPABASE_CLERK_SETUP.md Sets up a Supabase client for server-side operations within a Next.js application. It relies on environment variables for Supabase URL and Anon Key. ```typescript import { createSupabaseServerClient } from '@/lib/supabase' export async function getData() { const supabase = await createSupabaseServerClient() const { data, error } = await supabase .from('your_table') .select('*') return data } ``` -------------------------------- ### Next.js Root Layout Setup with ThemeProvider (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Demonstrates how to set up the root layout in a Next.js application to use the ThemeProvider for global theme management. It wraps the application with both ClerkProvider and the custom ThemeProvider, enabling theme persistence and system preference detection. This setup ensures themes are applied consistently across the entire app. ```typescript import { ClerkProvider } from "@clerk/nextjs"; import { ThemeProvider } from "@/components/theme-provider"; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( {children} ); } ``` -------------------------------- ### Environment Variables Configuration (Env) Source: https://github.com/yosrend/mahwa2006/blob/main/README.md Example `.env.local` file content showing necessary environment variables for Clerk authentication, Supabase integration, and optional AI services like OpenAI or Anthropic. These variables are essential for the application's functionality. ```env # Clerk Authentication NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_publishable_key CLERK_SECRET_KEY=your_secret_key # Supabase NEXT_PUBLIC_SUPABASE_URL=your_supabase_url NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key # AI Integration (Optional) OPENAI_API_KEY=your_openai_api_key ANTHROPIC_API_KEY=your_anthropic_api_key ``` -------------------------------- ### TypeScript Button Usage Examples Source: https://context7.com/yosrend/mahwa2006/llms.txt Illustrates various ways to use the Button component, including different variants, sizes, and incorporating icons. It also shows how to use the 'asChild' prop for rendering as a link and applying custom styles. ```typescript // Usage examples: import { Button } from "@/components/ui/button"; import { Download, Trash2 } from "lucide-react"; // Basic variants // Sizes // With icons // Disabled state // As link using Slot pattern (renders as instead of // Custom styling // Destructive with icon ``` -------------------------------- ### Add New Component in TypeScript Source: https://github.com/yosrend/mahwa2006/blob/main/CONTRIBUTING.md Example of creating a new UI component using TypeScript. It demonstrates defining props, using utility classes for styling, and basic component structure within a Next.js application context. ```typescript //src/components/ui/my-component.tsx import { cn } from "@/lib/utils" interface MyComponentProps { className?: string children: React.ReactNode } export function MyComponent({ className, children }: MyComponentProps) { return (
{children}
) } ``` -------------------------------- ### Themed UI Component Example with TailwindCSS Source: https://github.com/yosrend/mahwa2006/blob/main/CLAUDE.md Illustrates a theme-aware UI component using shadcn/ui and TailwindCSS. It applies CSS custom properties for background, foreground, and border colors, demonstrating how to integrate theming directly into the component's structure. ```typescript // Automatic dark mode support via CSS custom properties
``` -------------------------------- ### Create New Database Table with RLS Source: https://github.com/yosrend/mahwa2006/blob/main/CONTRIBUTING.md Example of a SQL migration script for creating a new database table and enabling Row Level Security (RLS). It sets up a table with standard columns and applies a policy to restrict access based on the authenticated user's ID. ```sql --supabase/migrations/002_new_feature.sql CREATE TABLE example_table ( id UUID DEFAULT gen_random_uuid() PRIMARY KEY, user_id TEXT NOT NULL, name TEXT NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW() ); ALTER TABLE example_table ENABLE ROW LEVEL SECURITY; CREATE POLICY "Users can manage own records" ON example_table FOR ALL USING (auth.jwt() ->> 'sub' = user_id); ``` -------------------------------- ### Supabase Row Level Security Policies Source: https://github.com/yosrend/mahwa2006/blob/main/SUPABASE_CLERK_SETUP.md SQL examples for creating Row Level Security (RLS) policies in Supabase to control access to data based on authenticated user IDs provided by Clerk's JWT. ```sql -- Enable RLS on your table ALTER TABLE your_table ENABLE ROW LEVEL SECURITY; -- Allow users to read their own data CREATE POLICY "Users can read own data" ON your_table FOR SELECT USING (auth.jwt() ->> 'sub' = user_id); -- Allow users to insert their own data CREATE POLICY "Users can insert own data" ON your_table FOR INSERT WITH CHECK (auth.jwt() ->> 'sub' = user_id); ``` -------------------------------- ### Supabase Client Usage with Clerk Token Source: https://github.com/yosrend/mahwa2006/blob/main/SUPABASE_CLERK_SETUP.md Demonstrates how to use the Supabase client on the client-side in a Next.js application, incorporating the authentication token obtained from Clerk to authorize requests. ```typescript import { supabase } from '@/lib/supabase' import { useAuth } from '@clerk/nextjs' function MyComponent() { const { getToken } = useAuth() const fetchData = async () => { const token = await getToken() const { data, error } = await supabase .from('your_table') .select('*') .auth(token) } } ``` -------------------------------- ### Client-side Supabase Client Usage (TypeScript) Source: https://github.com/yosrend/mahwa2006/blob/main/CLAUDE.md Illustrates how to interact with Supabase from the client-side in a Next.js application using Clerk authentication. This example shows fetching data by manually passing the authentication token obtained from Clerk's `useAuth` hook. ```typescript "use client" import { supabase } from "@/lib/supabase" import { useAuth } from "@clerk/nextjs" function ClientComponent() { const { getToken } = useAuth() const fetchData = async () => { const token = await getToken() // Pass token manually for client-side operations const { data, error } = await supabase .from('posts') .select('*') .auth(token) return data } } ``` -------------------------------- ### Simple Theme Toggle with Next-Themes (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Provides a simple button to toggle between light and dark themes, without a system option. It uses the 'next-themes' hook to get the current theme and switch between 'light' and 'dark'. This is suitable for interfaces where only explicit light/dark choices are needed. ```typescript "use client"; import * as React from "react"; import { Moon, Sun } from "lucide-react"; import { useTheme } from "next-themes"; import { Button } from "@/components/ui/button"; // Simple toggle between light and dark (no system option) export function SimpleThemeToggle() { const { theme, setTheme } = useTheme(); return ( ); } ``` -------------------------------- ### Get Current User with Clerk (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Retrieves the currently authenticated Clerk user object. This function is designed for use in server components and API routes, providing access to user details such as ID, name, and email. It relies on the `@clerk/nextjs/server` library. The example demonstrates its usage within a server component to display user information. ```typescript // File: src/lib/user.ts import { currentUser } from "@clerk/nextjs/server"; export async function getCurrentUser() { return await currentUser(); } // Usage in server component: import { getCurrentUser } from "@/lib/user"; export default async function ProfilePage() { const user = await getCurrentUser(); if (!user) { return
Please sign in
; } return (

Welcome, {user.firstName}

User ID: {user.id}

Email: {user.emailAddresses[0]?.emailAddress}

); } // User object includes: // - id: Clerk user ID (used for database relations) // - firstName, lastName: User name fields // - emailAddresses: Array of email objects // - imageUrl: Profile picture URL ``` -------------------------------- ### Create Documentation Directory - Bash Source: https://github.com/yosrend/mahwa2006/blob/main/README.md This command creates a new directory named 'documentation' in the current project root. This is the first step in organizing generated documentation files. ```bash mkdir documentation ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/yosrend/mahwa2006/blob/main/CLAUDE.md Lists essential environment variables required for the project's functionality, including those for Clerk authentication, Supabase database connection, and optional AI integrations. These variables should be set in the environment where the application runs. ```bash # Clerk Authentication NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_... CLERK_SECRET_KEY=sk_test_... # Supabase Database NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ... # AI Integration (optional) OPENAI_API_KEY=sk-... ANTHROPIC_API_KEY=sk-ant-... ``` -------------------------------- ### User Authentication API Source: https://context7.com/yosrend/mahwa2006/llms.txt This section covers utilities and middleware for handling user authentication using Clerk. ```APIDOC ## Get Current User ### Description Retrieve the authenticated Clerk user object. This function can be used in server components and API routes to access user details. ### Method GET (implicitly, via server-side function call) ### Endpoint N/A (This is a server-side utility function) ### Parameters None ### Request Example ```typescript import { getCurrentUser } from "@/lib/user"; export default async function ProfilePage() { const user = await getCurrentUser(); // ... use user object } ``` ### Response #### Success Response - **user** (object) - The authenticated user object containing details like `id`, `firstName`, `lastName`, `emailAddresses`, `imageUrl`, etc. #### Response Example ```json { "id": "user_123abc", "firstName": "John", "lastName": "Doe", "emailAddresses": [ {"emailAddress": "john.doe@example.com", "id": "email_456def"} ], "imageUrl": "https://example.com/image.jpg" } ``` #### Error Response - Returns `null` if the user is not authenticated. --- ## Route Protection Middleware ### Description Protects specified routes using Clerk middleware. Any requests to routes matching the defined patterns will require authentication. ### Method N/A (This is middleware configuration) ### Endpoint Configured via `src/middleware.ts` to protect routes like `/dashboard(.*)` and `/profile(.*)`. ### Parameters None ### Request Example (No direct request example, this is a server-side configuration) ### Response - **200 OK**: For authenticated users accessing protected routes or any user accessing public routes. - **401 Unauthorized**: For unauthenticated users attempting to access protected routes. ``` -------------------------------- ### Server-side Supabase Client Usage (TypeScript) Source: https://github.com/yosrend/mahwa2006/blob/main/CLAUDE.md Demonstrates how to fetch data from Supabase on the server-side using the `createSupabaseServerClient` function. This is the recommended approach for data fetching in Next.js applications integrated with Clerk authentication. ```typescript import { createSupabaseServerClient } from "@/lib/supabase" export async function getServerData() { const supabase = await createSupabaseServerClient() const { data, error } = await supabase .from('posts') .select('*') .order('created_at', { ascending: false }) if (error) { console.error('Database error:', error) return null } return data } ``` -------------------------------- ### SQL: Create Tables and Enable RLS Policies Source: https://context7.com/yosrend/mahwa2006/llms.txt Defines tables such as posts, private_notes, collaborations, and profiles, enabling Row Level Security for each. Policies are set to control data access based on authenticated user IDs (Clerk `sub` from JWT), ensuring multi-tenant isolation and user-specific data management. ```sql -- File: supabase/migrations/001_example_tables_with_rls.sql -- Create posts table with Clerk user_id CREATE TABLE IF NOT EXISTS public.posts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), title TEXT NOT NULL, content TEXT, user_id TEXT NOT NULL, -- Stores Clerk user ID created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Enable Row Level Security ALTER TABLE public.posts ENABLE ROW LEVEL SECURITY; -- Public read access CREATE POLICY "Anyone can read posts" ON public.posts FOR SELECT USING (true); -- Users can only insert as themselves CREATE POLICY "Users can insert own posts" ON public.posts FOR INSERT WITH CHECK (auth.jwt() ->> 'sub' = user_id); -- Users can only update their own posts CREATE POLICY "Users can update own posts" ON public.posts FOR UPDATE USING (auth.jwt() ->> 'sub' = user_id); -- Users can only delete their own posts CREATE POLICY "Users can delete own posts" ON public.posts FOR DELETE USING (auth.jwt() ->> 'sub' = user_id); -- Private notes example (completely private to each user) CREATE TABLE IF NOT EXISTS public.private_notes ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), title TEXT NOT NULL, content TEXT, user_id TEXT NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); ALTER TABLE public.private_notes ENABLE ROW LEVEL SECURITY; -- Only owner can access CREATE POLICY "Users can only access own private notes" ON public.private_notes FOR ALL USING (auth.jwt() ->> 'sub' = user_id); -- Collaboration example (owner and collaborators access) CREATE TABLE IF NOT EXISTS public.collaborations ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name TEXT NOT NULL, description TEXT, owner_id TEXT NOT NULL, collaborators TEXT[] DEFAULT '{}', -- Array of Clerk user IDs created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); ALTER TABLE public.collaborations ENABLE ROW LEVEL SECURITY; -- Owner and collaborators can read CREATE POLICY "Owners and collaborators can read collaborations" ON public.collaborations FOR SELECT USING ( auth.jwt() ->> 'sub' = owner_id OR auth.jwt() ->> 'sub' = ANY(collaborators) ); -- Only owner can modify CREATE POLICY "Owners can update collaborations" ON public.collaborations FOR UPDATE USING (auth.jwt() ->> 'sub' = owner_id); -- Profiles with conditional visibility CREATE TABLE IF NOT EXISTS public.profiles ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id TEXT UNIQUE NOT NULL, bio TEXT, website TEXT, avatar_url TEXT, is_public BOOLEAN DEFAULT false, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY; -- Read public profiles or own profile CREATE POLICY "Users can read public profiles or own profile" ON public.profiles FOR SELECT USING ( is_public = true OR auth.jwt() ->> 'sub' = user_id ); ``` -------------------------------- ### Next.js Root Layout with Providers (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Configures the main layout for a Next.js application, integrating Clerk for authentication, Next Themes for theme management, and Google Fonts for typography. It sets up a global provider hierarchy ensuring authentication, theme, and font styles are applied across the application. ```typescript // File: src/app/layout.tsx import type { Metadata } from "next"; import { Geist, Geist_Mono, Parkinsans } from "next/font/google"; import { ClerkProvider } from "@clerk/nextjs"; import { ThemeProvider } from "@/components/theme-provider"; import "./globals.css"; const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"], }); const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"], }); const parkinsans = Parkinsans({ variable: "--font-parkinsans", subsets: ["latin"], weight: ["300", "400", "500", "600", "700", "800"], fallback: ["system-ui", "sans-serif"], adjustFontFallback: false, }); export const metadata: Metadata = { title: "CodeGuide Starter Kit", description: "A modern Next.js starter with TypeScript, TailwindCSS, shadcn/ui, Vercel AI SDK, Clerk, and Supabase", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode }> ): React.JSX.Element { return ( {children} ); } // Provider hierarchy: // 1. ClerkProvider: Authentication context for entire app // 2. html[suppressHydrationWarning]: Prevents theme flash on load // 3. ThemeProvider: Dark mode management with system detection // 4. Font classes: Applied to body for global typography // Access providers in components: import { useAuth, useUser } from "@clerk/nextjs"; import { useTheme } from "next-themes"; function MyComponent() { const { userId, isSignedIn } = useAuth(); const { user } = useUser(); const { theme, setTheme } = useTheme(); return (
{isSignedIn &&

User ID: {userId}

} {user &&

Email: {user.emailAddresses[0]?.emailAddress}

}

Current theme: {theme}

); } // Fonts available as CSS variables: // - var(--font-geist-sans) // - var(--font-geist-mono) // - var(--font-parkinsans) ``` -------------------------------- ### Supabase CRUD Operations for Posts (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Provides functions for performing Create, Read, Update, and Delete operations on the 'posts' table using the server-side Supabase client. These functions require a user to be authenticated via Clerk. ```typescript // Usage example - Server component CRUD operations: import { createSupabaseServerClient } from "@/lib/supabase"; import { getCurrentUser } from "@/lib/user"; // CREATE - Insert new post export async function createPost(title: string, content: string) { const user = await getCurrentUser(); if (!user) return null; const supabase = await createSupabaseServerClient(); const { data, error } = await supabase .from('posts') .insert({ title, content, user_id: user.id }) .select() .single(); if (error) { console.error('Error creating post:', error); return null; } return data; } // READ - Fetch user's posts with ordering export async function getUserPosts() { const supabase = await createSupabaseServerClient(); const { data, error } = await supabase .from('posts') .select('id, title, content, created_at, user_id') .order('created_at', { ascending: false }); if (error) { console.error('Error fetching posts:', error); return []; } return data; } // UPDATE - Modify existing post export async function updatePost(postId: string, updates: { title?: string; content?: string }) { const supabase = await createSupabaseServerClient(); const { data, error } = await supabase .from('posts') .update(updates) .eq('id', postId) .select() .single(); if (error) { console.error('Error updating post:', error); return null; } return data; } // DELETE - Remove post export async function deletePost(postId: string) { const supabase = await createSupabaseServerClient(); const { error } = await supabase .from('posts') .delete() .eq('id', postId); if (error) { console.error('Error deleting post:', error); return false; } return true; } ``` -------------------------------- ### Create Supabase Server Client (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Initializes a Supabase client for server-side operations in Next.js. It automatically injects Clerk authentication tokens for RLS, ensuring secure data access. Requires Supabase URL, Anon Key, and Clerk integration. ```typescript // File: src/lib/supabase.ts import { createClient } from "@supabase/supabase-js"; import { auth } from "@clerk/nextjs/server"; const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!; const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!; // Client-side Supabase client (manual token management required) export const supabase = createClient(supabaseUrl, supabaseAnonKey, { global: { fetch: (url, options = {}) => { return fetch(url, { ...options, cache: "no-store" }); }, }, }); // Server-side Supabase client (automatic Clerk token injection) export async function createSupabaseServerClient() { const { getToken } = await auth(); const token = await getToken(); return createClient(supabaseUrl, supabaseAnonKey, { global: { headers: { Authorization: token ? `Bearer ${token}` : "", }, fetch: (url, options = {}) => { return fetch(url, { ...options, cache: "no-store" }); }, }, }); } ``` -------------------------------- ### Supabase CRUD Operations in TypeScript Source: https://github.com/yosrend/mahwa2006/blob/main/CLAUDE.md Demonstrates complete Create, Read, Update, and Delete operations for posts using Supabase. It requires authentication via `getCurrentUser` and a Supabase client initialized with `createSupabaseServerClient`. It returns the created/updated data or a boolean for deletion success. ```typescript import { createSupabaseServerClient } from "@/lib/supabase" import { getCurrentUser } from "@/lib/user" // CREATE - Insert new record export async function createPost(title: string, content: string) { const user = await getCurrentUser() if (!user) return null const supabase = await createSupabaseServerClient() const { data, error } = await supabase .from('posts') .insert({ title, content, user_id: user.id, // Clerk user ID }) .select() .single() if (error) { console.error('Error creating post:', error) return null } return data } // READ - Fetch user's posts export async function getUserPosts() { const supabase = await createSupabaseServerClient() const { data, error } = await supabase .from('posts') .select( ` id, title, content, created_at, user_id `) .order('created_at', { ascending: false }) if (error) { console.error('Error fetching posts:', error) return [] } return data } // UPDATE - Modify existing record export async function updatePost(postId: string, updates: { title?: string; content?: string }) { const supabase = await createSupabaseServerClient() const { data, error } = await supabase .from('posts') .update(updates) .eq('id', postId) .select() .single() if (error) { console.error('Error updating post:', error) return null } return data } // DELETE - Remove record export async function deletePost(postId: string) { const supabase = await createSupabaseServerClient() const { error } = await supabase .from('posts') .delete() .eq('id', postId) if (error) { console.error('Error deleting post:', error) return false } return true } ``` -------------------------------- ### Component Patterns in TypeScript (Next.js) Source: https://github.com/yosrend/mahwa2006/blob/main/CLAUDE.md Illustrates the use of 'use client' directive for client components in Next.js, which are necessary for interactivity and hooks, and the default server component pattern for data fetching. ```typescript // Client components (when using hooks/state) "use client" // Server components (default, for data fetching) export default async function ServerComponent() { const user = await getCurrentUser() // ... } ``` -------------------------------- ### Dropdown Theme Toggle with Next-Themes (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Implements a dropdown menu for theme selection (light, dark, system) using next-themes and shadcn/ui components. It requires 'lucide-react' for icons and 'next-themes' for theme management. This component provides a user-friendly way to switch between different theme modes. ```typescript "use client"; import * as React from "react"; import { Moon, Sun } from "lucide-react"; import { useTheme } from "next-themes"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; // Dropdown theme toggle with light/dark/system options export function ThemeToggle() { const { setTheme } = useTheme(); return ( setTheme("light")}> Light setTheme("dark")}> Dark setTheme("system")}> System ); } ``` -------------------------------- ### AI Chat Component using Vercel AI SDK (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt A React component that implements a real-time chat interface. It uses the `useChat` hook from the Vercel AI SDK to manage messages, input, submission, and loading states. Includes UI elements for displaying user and AI messages, error notifications, and an input form. Dependencies include various UI components from `@/components/ui` and icons from `lucide-react`. ```typescript "use client"; import { useChat } from "ai/react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Card } from "@/components/ui/card"; import { AlertCircle, Bot, User } from "lucide-react"; export default function Chat() { const { messages, input, handleInputChange, handleSubmit, error, isLoading: chatLoading, } = useChat({ onError: (error) => { console.error("Chat error:", error); }, }); return (

🤖 AI Chat

Powered by OpenAI GPT-4o • Protected by Clerk Authentication

{error && (
{error.message || "An error occurred while processing your request."}
)}
{messages.length === 0 ? (

Start a conversation

Ask me anything! I'm here to help with coding, questions, or just chat.

) : ( messages.map((m) => (
{m.role === "user" ? ( ) : ( )} {m.role === "user" ? "You" : "AI Assistant"}
{m.content}
)) )} {chatLoading && (
AI Assistant
)}
); } ``` -------------------------------- ### Supabase Real-time Post Subscriptions in TypeScript Source: https://github.com/yosrend/mahwa2006/blob/main/CLAUDE.md Implements a custom React hook `useRealtimePosts` to fetch posts from Supabase and subscribe to real-time changes. It uses Clerk for authentication via `getToken` and establishes a PostgreSQL channel subscription for the 'posts' table. It refetches posts on any change. ```typescript "use client" import { useEffect, useState } from "react" import { supabase } from "@/lib/supabase" import { useAuth } from "@clerk/nextjs" function useRealtimePosts() { const [posts, setPosts] = useState([]) const { getToken } = useAuth() useEffect(() => { const fetchPosts = async () => { const token = await getToken() const { data } = await supabase .from('posts') .select('*') .auth(token) setPosts(data || []) } fetchPosts() // Subscribe to changes const subscription = supabase .channel('posts-channel') .on('postgres_changes', { event: '*', schema: 'public', table: 'posts' }, (payload) => { fetchPosts() // Refetch on any change } ) .subscribe() return () => { subscription.unsubscribe() } }, [getToken]) return posts } ``` -------------------------------- ### ThemeProvider Component for Next.js (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt A wrapper component that integrates the 'next-themes' ThemeProvider into a Next.js application. It accepts standard ThemeProviderProps, including 'attribute', 'defaultTheme', and 'enableSystem', allowing for global theme configuration. This component is typically used in the root layout file. ```typescript "use client"; import * as React from "react"; import { ThemeProvider as NextThemesProvider } from "next-themes"; import { type ThemeProviderProps } from "next-themes"; export function ThemeProvider({ children, ...props }: ThemeProviderProps) { return {children}; } ``` -------------------------------- ### Client-side Supabase Usage with Clerk Token (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Demonstrates how to use the client-side Supabase instance within a React component using Clerk's `useAuth` hook. It shows fetching data after manually obtaining the authentication token. ```typescript // Client-side usage with manual token: "use client" import { supabase } from "@/lib/supabase"; import { useAuth } from "@clerk/nextjs"; function ClientComponent() { const { getToken } = useAuth(); const fetchData = async () => { const token = await getToken(); const { data, error } = await supabase .from('posts') .select('*') .order('created_at', { ascending: false }); return data; }; } ``` -------------------------------- ### Protect Routes with Clerk Middleware (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Implements route protection using Clerk's middleware capabilities. This configuration defines specific routes (e.g., `/dashboard`, `/profile`) that require authentication. It uses `createRouteMatcher` for pattern matching and `clerkMiddleware` to enforce protection. Public routes remain accessible without authentication. Client-side components for sign-in and user display are also shown. ```typescript // File: src/middleware.ts import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server"; const isProtectedRoute = createRouteMatcher(["/dashboard(.*)", "/profile(.*)"]); export default clerkMiddleware(async (auth, req) => { if (isProtectedRoute(req)) await auth.protect(); }); export const config = { matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"], }; // Protected routes: // - /dashboard → Requires authentication // - /dashboard/settings → Requires authentication // - /profile → Requires authentication // - /profile/edit → Requires authentication // - / → Public access // - /about → Public access // Client-side authentication components: import { SignInButton, SignedIn, SignedOut, UserButton } from "@clerk/nextjs"; function Header() { return (
{/* Shows user profile dropdown */}
); } ``` -------------------------------- ### Import Statements in TypeScript Source: https://github.com/yosrend/mahwa2006/blob/main/CLAUDE.md Demonstrates path aliasing for internal modules and importing external libraries in TypeScript projects. Path aliases are typically configured in `tsconfig.json`. ```typescript // Path aliases (configured in tsconfig.json) import { Button } from "@/components/ui/button" import { getCurrentUser } from "@/lib/user" import { supabase } from "@/lib/supabase" // External libraries import { useTheme } from "next-themes" import { SignedIn, useAuth } from "@clerk/nextjs" ``` -------------------------------- ### Stream AI Chat with OpenAI and Clerk Auth (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Implements a streaming AI chat interface using the Vercel AI SDK with OpenAI's GPT-4o model. This endpoint is protected by Clerk authentication, ensuring only authenticated users can access it. It handles JSON requests containing chat messages and returns a streaming text response. Error handling for missing API keys and request failures is included. ```typescript // File: src/app/api/chat/route.ts import { openai } from "@ai-sdk/openai"; import { streamText } from "ai"; import { auth } from "@clerk/nextjs/server"; export async function POST(req: Request) { const { userId } = await auth(); if (!userId) { return new Response("Unauthorized", { status: 401 }); } if (!process.env.OPENAI_API_KEY) { return new Response( JSON.stringify({ error: "OpenAI API key not configured. Please add OPENAI_API_KEY to your environment variables.", }), { status: 500, headers: { "Content-Type": "application/json" } } ); } try { const { messages } = await req.json(); const result = streamText({ model: openai("gpt-4o"), messages, }); return result.toDataStreamResponse(); } catch (error) { console.error("Chat API error:", error); return new Response( JSON.stringify({ error: "Failed to process chat request." }), { status: 500, headers: { "Content-Type": "application/json" } } ); } } // Client-side usage with curl: // curl -X POST http://localhost:3000/api/chat \ // -H "Content-Type: application/json" \ // -H "Authorization: Bearer " \ // -d '{"messages":[{"role":"user","content":"Hello!"}]}' // Expected response: Streaming text response with data chunks ``` -------------------------------- ### Themed Button with Shadcn/ui (TypeScript) Source: https://context7.com/yosrend/mahwa2006/llms.txt Shows how to use a shadcn/ui Button component that automatically inherits theme colors from CSS custom properties. By applying classes like 'bg-background' and 'text-foreground', the button's appearance dynamically adjusts based on the application's current theme (light or dark). ```typescript import { Button } from "@/components/ui/button"; function ThemedButton() { return ( ); } ``` -------------------------------- ### AI Chat Streaming Endpoint Source: https://context7.com/yosrend/mahwa2006/llms.txt This endpoint provides a streaming AI chat interface using the Vercel AI SDK with the OpenAI GPT-4o model. It is protected by Clerk authentication, ensuring only authenticated users can access it. The endpoint expects a JSON payload containing an array of messages and returns a data stream response. ```APIDOC ## POST /api/chat ### Description Provides a streaming AI chat interface using Vercel AI SDK with OpenAI GPT-4o model and Clerk authentication protection. ### Method POST ### Endpoint /api/chat ### Parameters #### Query Parameters None #### Request Body - **messages** (array) - Required - An array of message objects, each with a `role` (e.g., 'user', 'assistant') and `content` (string). ### Request Example ```json { "messages": [ {"role": "user", "content": "Hello!"} ] } ``` ### Response #### Success Response (200) - **dataStream** (ReadableStream) - A stream of text chunks representing the AI's response. #### Response Example (Streaming text response with data chunks, not a static JSON object) #### Error Response (401) - **Unauthorized** (string) - Returned if the user is not authenticated. #### Error Response (500) - **error** (string) - "OpenAI API key not configured. Please add OPENAI_API_KEY to your environment variables." or "Failed to process chat request." ```