diff --git a/Complete Next.js-Supabase Development Guide 2025 b/Complete Next.js-Supabase Development Guide 2025 new file mode 100644 index 0000000..0d3ee14 --- /dev/null +++ b/Complete Next.js-Supabase Development Guide 2025 @@ -0,0 +1,1535 @@ +# Complete Next.js + Supabase Development Guide 2025 + +**A comprehensive, standalone guide for building production-ready applications with Next.js 15 and Supabase** + +This guide covers everything from project setup to deployment, including authentication, database operations, TypeScript integration, and modern best practices. Perfect for beginners and as a reference for experienced developers. + +--- + +## Table of Contents +1. [Prerequisites & Initial Setup](#prerequisites--initial-setup) +2. [Project Creation & Configuration](#project-creation--configuration) +3. [Supabase Integration](#supabase-integration) +4. [Project Structure](#project-structure) +5. [Database Schema & Security](#database-schema--security) +6. [Authentication Implementation](#authentication-implementation) +7. [CRUD Operations](#crud-operations) +8. [UI Components & Styling](#ui-components--styling) +9. [Error Handling & Loading States](#error-handling--loading-states) +10. [TypeScript Configuration](#typescript-configuration) +11. [Deployment & Production](#deployment--production) +12. [Complete Code Examples](#complete-code-examples) + +--- + +## Prerequisites & Initial Setup + +### System Requirements +- **Node.js**: 18.17.0 or higher +- **npm**: 9.0.0 or higher (or yarn/pnpm equivalent) +- **Git**: For version control +- **Code Editor**: VS Code recommended + +### Version Requirements (2025) +- **Next.js**: 15.x (latest) +- **React**: 19 RC +- **Supabase JS**: 2.50.1+ +- **TypeScript**: 5.1.3+ +- **Tailwind CSS**: 4.x + +### Supabase Account Setup +1. Go to [supabase.com](https://supabase.com) +2. Sign up for a free account +3. Create a new project +4. Choose a database password (save it securely) +5. Wait for project initialization (~2 minutes) + +--- + +## Project Creation & Configuration + +### 1. Create Next.js Application + +```bash +npx create-next-app@latest my-supabase-app +``` + +**Choose these options when prompted:** +``` +✓ Would you like to use TypeScript? → Yes +✓ Would you like to use ESLint? → Yes +✓ Would you like to use Tailwind CSS? → Yes +✓ Would you like to use `src/` directory? → Yes +✓ Would you like to use App Router? → Yes +✓ Would you like to use Turbopack for `next dev`? → Yes +✓ Would you like to customize the default import alias (@/*)? → Yes +``` + +### 2. Navigate to Project & Install Dependencies + +```bash +cd my-supabase-app +npm install @supabase/supabase-js @supabase/ssr +``` + +**Important**: Don't install `@supabase/auth-helpers-nextjs` - it's deprecated. Use `@supabase/ssr` instead. + +### 3. Environment Variables Setup + +Create `.env.local` in your project root: + +```env +# Supabase Configuration +NEXT_PUBLIC_SUPABASE_URL=your_supabase_project_url +NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key + +# Optional: For admin operations (keep secure, never expose to client) +SUPABASE_SERVICE_ROLE_KEY=your_service_role_key +``` + +**To find your Supabase credentials:** +1. Go to your Supabase project dashboard +2. Click on "Settings" → "API" +3. Copy "Project URL" and "anon public" key + +--- + +## Supabase Integration + +### 1. Client-Side Supabase Client + +Create `src/lib/supabase/client.ts`: + +```typescript +import { createBrowserClient } from '@supabase/ssr' + +export function createClient() { + return createBrowserClient( + process.env.NEXT_PUBLIC_SUPABASE_URL!, + process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! + ) +} +``` + +### 2. Server-Side Supabase Client + +Create `src/lib/supabase/server.ts`: + +```typescript +import { createServerClient } from '@supabase/ssr' +import { cookies } from 'next/headers' + +export async function createClient() { + const cookieStore = await cookies() + + return createServerClient( + process.env.NEXT_PUBLIC_SUPABASE_URL!, + process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, + { + cookies: { + getAll() { + return cookieStore.getAll() + }, + setAll(cookiesToSet) { + try { + cookiesToSet.forEach(({ name, value, options }) => { + cookieStore.set(name, value, options) + }) + } catch { + // Server component case - cookies can't be set + } + }, + }, + } + ) +} +``` + +### 3. Session Management Middleware + +Create `middleware.ts` in your project root (same level as `package.json`): + +```typescript +import { type NextRequest } from 'next/server' +import { updateSession } from '@/lib/supabase/middleware' + +export async function middleware(request: NextRequest) { + return await updateSession(request) +} + +export const config = { + matcher: [ + '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)', + ], +} +``` + +Create `src/lib/supabase/middleware.ts`: + +```typescript +import { createServerClient } from '@supabase/ssr' +import { NextResponse, type NextRequest } from 'next/server' + +export async function updateSession(request: NextRequest) { + let supabaseResponse = NextResponse.next({ + request, + }) + + const supabase = createServerClient( + process.env.NEXT_PUBLIC_SUPABASE_URL!, + process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, + { + cookies: { + getAll() { + return request.cookies.getAll() + }, + setAll(cookiesToSet) { + cookiesToSet.forEach(({ name, value, options }) => { + request.cookies.set(name, value) + supabaseResponse.cookies.set(name, value, options) + }) + }, + }, + } + ) + + // Refresh session if needed + const { data: { user } } = await supabase.auth.getUser() + + return supabaseResponse +} +``` + +--- + +## Project Structure + +### Recommended File Organization + +``` +my-supabase-app/ +├── src/ +│ ├── app/ # App Router (Next.js 13+) +│ │ ├── globals.css # Global styles +│ │ ├── layout.tsx # Root layout +│ │ ├── page.tsx # Home page +│ │ ├── loading.tsx # Global loading UI +│ │ ├── error.tsx # Global error boundary +│ │ ├── not-found.tsx # 404 page +│ │ │ +│ │ ├── (auth)/ # Route groups for organization +│ │ │ ├── login/ +│ │ │ │ ├── page.tsx +│ │ │ │ ├── actions.ts # Server actions +│ │ │ │ └── loading.tsx +│ │ │ └── signup/ +│ │ │ └── page.tsx +│ │ │ +│ │ ├── dashboard/ # Protected routes +│ │ │ ├── layout.tsx # Dashboard layout +│ │ │ ├── page.tsx +│ │ │ ├── actions.ts # Server actions for dashboard +│ │ │ ├── loading.tsx +│ │ │ ├── error.tsx +│ │ │ └── tasks/ +│ │ │ └── page.tsx +│ │ │ +│ │ └── api/ # API routes +│ │ └── auth/ +│ │ └── confirm/ +│ │ └── route.ts # Email confirmation +│ │ +│ ├── components/ # Reusable components +│ │ ├── ui/ # Basic UI components (shadcn/ui) +│ │ │ ├── button.tsx +│ │ │ ├── card.tsx +│ │ │ ├── input.tsx +│ │ │ └── skeleton.tsx +│ │ ├── layout/ # Layout components +│ │ │ ├── header.tsx +│ │ │ ├── nav.tsx +│ │ │ └── footer.tsx +│ │ └── features/ # Feature-specific components +│ │ ├── auth/ +│ │ │ ├── login-form.tsx +│ │ │ └── logout-button.tsx +│ │ └── tasks/ +│ │ ├── task-list.tsx +│ │ └── task-form.tsx +│ │ +│ ├── lib/ # Utility libraries +│ │ ├── utils.ts # General utilities +│ │ ├── dal.ts # Data Access Layer (security) +│ │ ├── validations.ts # Schema validations +│ │ └── supabase/ # Supabase configuration +│ │ ├── client.ts # Client-side client +│ │ ├── server.ts # Server-side client +│ │ └── middleware.ts # Session management +│ │ +│ ├── hooks/ # Custom React hooks +│ │ ├── use-auth.ts +│ │ └── use-local-storage.ts +│ │ +│ └── types/ # TypeScript definitions +│ └── database.types.ts # Generated Supabase types +│ +├── middleware.ts # Next.js middleware +├── next.config.ts # Next.js configuration +├── tailwind.config.ts # Tailwind configuration +├── tsconfig.json # TypeScript configuration +└── package.json +``` + +--- + +## Database Schema & Security + +### 1. Create Tables in Supabase + +Go to your Supabase project → SQL Editor → New Query, and run: + +```sql +-- Create the tasks table +CREATE TABLE tasks ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + title TEXT NOT NULL, + description TEXT, + completed BOOLEAN DEFAULT FALSE, + user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL +); + +-- Enable Row Level Security (RLS) +ALTER TABLE tasks ENABLE ROW LEVEL SECURITY; + +-- Create security policies +CREATE POLICY "Users can view own tasks" ON tasks + FOR SELECT USING (auth.uid() = user_id); + +CREATE POLICY "Users can insert own tasks" ON tasks + FOR INSERT WITH CHECK (auth.uid() = user_id); + +CREATE POLICY "Users can update own tasks" ON tasks + FOR UPDATE USING (auth.uid() = user_id); + +CREATE POLICY "Users can delete own tasks" ON tasks + FOR DELETE USING (auth.uid() = user_id); + +-- Create indexes for performance +CREATE INDEX idx_tasks_user_id ON tasks(user_id); +CREATE INDEX idx_tasks_created_at ON tasks(created_at DESC); + +-- Add updated_at trigger +CREATE OR REPLACE FUNCTION update_updated_at_column() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = TIMEZONE('utc'::text, NOW()); + RETURN NEW; +END; +$$ language 'plpgsql'; + +CREATE TRIGGER update_tasks_updated_at + BEFORE UPDATE ON tasks + FOR EACH ROW + EXECUTE FUNCTION update_updated_at_column(); +``` + +### 2. Generate TypeScript Types + +Run this command to generate types from your database: + +```bash +npx supabase gen types typescript --project-id your_project_id > src/types/database.types.ts +``` + +Replace `your_project_id` with your actual Supabase project ID (found in Project Settings → General). + +--- + +## Authentication Implementation + +### 1. Data Access Layer (Security) + +Create `src/lib/dal.ts`: + +```typescript +import 'server-only' +import { redirect } from 'next/navigation' +import { createClient } from '@/lib/supabase/server' +import { cache } from 'react' + +export const verifySession = cache(async () => { + const supabase = await createClient() + const { data: { user }, error } = await supabase.auth.getUser() + + if (error || !user) { + redirect('/login') + } + + return { isAuth: true, user } +}) + +export const getUser = cache(async () => { + const session = await verifySession() + if (!session) return null + + return session.user +}) +``` + +### 2. Login Page + +Create `src/app/(auth)/login/page.tsx`: + +```typescript +import { login, signup } from './actions' + +export default function LoginPage() { + return ( +
Welcome back, {session.user.email}
+No tasks yet. Create your first task!
++ {task.description} +
+ )} ++ Created {formatDate(task.created_at)} +
++ An error occurred while loading this page. +
+ +Loading...
++ The page you're looking for doesn't exist. +
+ + Go to Dashboard + ++ A modern full-stack application template +
+{{ agent.description }}
-👋 Welcome to the 5 Whys Root Cause Analysis!
-I'll help you systematically analyze your problem using the proven 5 Whys methodology.
-To get started, please describe the problem you're experiencing.
-For example:
-What problem would you like to analyze?
-Drop your file here or click to browse
-Supports CSV, Excel, JSON files up to 10MB
- - -- - Top up wallet - to use this agent -
- {% endif %} -Don't have an account? Register here
+ +Email: {{ user.email }}
+Balance: ${{ user.wallet_balance }}
+ +No transactions yet.
+ {% endif %} +Already have an account? Login here
+ +{{ agent.description }}
+ + {% if user.is_authenticated %} +Login to use this agent.
+ {% endif %} +Please check back later or contact the administrator.
+No transactions yet.
+ {% endif %} +This debug page is only available in development mode.
- {% else %} -{{ env_status|safe }}
- Database Connection: {{ db_status.status }}
-User Count: {{ user_count }}
-Agent Count: {{ agent_count }}
-- Tailored strategies for your business -
-- Tailored strategies, advanced threat detection, and comprehensive security frameworks to protect your digital assets and business operations. -
-- Empower your Business with AI. Strategic AI adoption, machine learning solutions, and intelligent automation to transform your processes. -
-- Rapid response to minimize damage. Emergency incident response and real-time threat mitigation to protect your business. -
-Food & Beverage Industry
-Manufacturing & Processing
-Technology Consulting
-Supply Chain Management
-- Founder & Principal Consultant -
-- Our Founder leverages over 18 years of expertise in cybersecurity and process automation and optimization, backed by top certifications in Cybersecurity and Black Belt in Lean Six Sigma. -
-- His unique blend of technical knowledge and operational excellence ensures tailored, secure, and efficient solutions for our clients, driving business resilience and maximizing value in every engagement. -
-- "Delivering top-tier solutions that combine cutting-edge technology with proven operational methodologies to secure and optimize your business operations." -
-
- Meydan Grandstand, 6th floor
- Meydan Road, Nad Al Sheba
- Dubai, U.A.E.
-
- We are committed to deliver top-tier AI & Cybersecurity solutions for businesses of all sizes. -
-Choose from our collection of powerful AI agents
-{{ agent.description }}
- -- Enter your new password below -
-