> ## Documentation Index
> Fetch the complete documentation index at: https://docs.weventures.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Next.js

> Our primary framework for web applications

## What is Next.js?

<Tabs>
  <Tab title="For Beginners">
    Next.js is a **React framework** that helps you build full-stack web applications with ease. Think of it as React with superpowers:

    * **React** lets you build interactive user interfaces using components
    * **Next.js** adds powerful features like server-side rendering, routing, and API endpoints out of the box

    Instead of configuring everything yourself (bundlers, routers, servers), Next.js provides a complete solution so you can focus on building your app. It's like having a pre-built house foundation instead of starting from scratch.

    **Key benefits for learners:**

    * File-based routing (create a file, get a page automatically)
    * Built-in optimization for performance and SEO
    * Can handle both frontend and backend code in one project
    * Excellent documentation and large community support
  </Tab>

  <Tab title="Why We Use It">
    Next.js is our go-to framework for building production-ready web applications with excellent developer experience. It provides enterprise-grade features while maintaining simplicity.
  </Tab>
</Tabs>

<CardGroup cols={3}>
  <Card title="SSR/ISR" icon="server">
    Server-side rendering and incremental static regeneration
  </Card>

  <Card title="API Routes" icon="plug">
    Built-in API layer with middleware support
  </Card>

  <Card title="App Router" icon="route">
    Modern routing with layouts and loading states
  </Card>
</CardGroup>

## When to Use

<Tabs>
  <Tab title="Always Use For">
    * Full-stack applications
    * SEO-critical sites
    * E-commerce platforms
    * Dashboards with auth
    * Real-time features
  </Tab>

  <Tab title="Consider Alternatives">
    * Pure marketing sites → Framer
    * Static documentation → Mintlify
    * Mobile apps → React Native
    * Simple APIs → Supabase Edge Functions
  </Tab>
</Tabs>

## Project Setup

<Steps>
  <Step title="Create New Project">
    ```bash theme={null}
    pnpm create next-app@latest my-app --typescript --tailwind --app --src-dir
    ```
  </Step>

  <Step title="Add Essential Packages">
    ```bash theme={null}
    pnpm add @supabase/supabase-js @tanstack/react-query zod
    pnpm add -D @types/node
    ```
  </Step>

  <Step title="Configure TypeScript">
    ```json theme={null}
    {
      "compilerOptions": {
        "strict": true,
        "noUncheckedIndexedAccess": true,
        "paths": {
          "@/*": ["./src/*"]
        }
      }
    }
    ```
  </Step>
</Steps>

## Best Practices

### File Structure

```
src/
├── app/
│   ├── (auth)/
│   │   ├── login/
│   │   └── register/
│   ├── (dashboard)/
│   │   └── layout.tsx
│   ├── api/
│   │   └── route.ts
│   └── layout.tsx
├── components/
│   ├── ui/
│   └── features/
├── lib/
│   ├── supabase.ts
│   └── utils.ts
└── types/
```

### Data Fetching

<CodeGroup>
  ```typescript Server Component theme={null}
  // app/products/page.tsx
  async function ProductsPage() {
    const products = await fetch('https://api.example.com/products', {
      next: { revalidate: 3600 } // ISR: revalidate every hour
    }).then(res => res.json())

    return <ProductList products={products} />
  }
  ```

  ```typescript Client Component theme={null}
  // components/user-profile.tsx
  'use client'

  import { useQuery } from '@tanstack/react-query'

  export function UserProfile() {
    const { data, isLoading } = useQuery({
      queryKey: ['user'],
      queryFn: fetchUser
    })

    if (isLoading) return <Skeleton />
    return <Profile user={data} />
  }
  ```
</CodeGroup>

### API Routes

<CodeGroup>
  ```typescript Route Handler theme={null}
  // app/api/users/route.ts
  import { NextRequest, NextResponse } from 'next/server'
  import { z } from 'zod'

  const userSchema = z.object({
    name: z.string().min(1),
    email: z.string().email()
  })

  export async function POST(request: NextRequest) {
    try {
      const body = await request.json()
      const validated = userSchema.parse(body)

      // Create user in database
      const user = await createUser(validated)

      return NextResponse.json(user, { status: 201 })
    } catch (error) {
      if (error instanceof z.ZodError) {
        return NextResponse.json(
          { error: error.errors },
          { status: 400 }
        )
      }
      return NextResponse.json(
        { error: 'Internal server error' },
        { status: 500 }
      )
    }
  }
  ```

  ```typescript Server Actions theme={null}
  // app/actions.ts
  'use server'

  import { revalidatePath } from 'next/cache'

  export async function createPost(formData: FormData) {
    const title = formData.get('title') as string
    const content = formData.get('content') as string

    await db.post.create({
      data: { title, content }
    })

    revalidatePath('/posts')
  }
  ```
</CodeGroup>

## Performance Optimization

<Accordion title="Image Optimization">
  ```tsx theme={null}
  import Image from 'next/image'

  <Image
    src="/hero.jpg"
    alt="Hero"
    width={1920}
    height={1080}
    priority // Load immediately for above-the-fold
    placeholder="blur"
    blurDataURL={blurDataUrl}
  />
  ```
</Accordion>

<Accordion title="Dynamic Imports">
  ```tsx theme={null}
  import dynamic from 'next/dynamic'

  const HeavyComponent = dynamic(
    () => import('@/components/HeavyComponent'),
    {
      loading: () => <Skeleton />,
      ssr: false // Disable SSR for client-only components
    }
  )
  ```
</Accordion>

<Accordion title="Metadata API">
  ```tsx theme={null}
  // app/products/[id]/page.tsx
  export async function generateMetadata({ params }) {
    const product = await getProduct(params.id)

    return {
      title: product.name,
      description: product.description,
      openGraph: {
        images: [product.image]
      }
    }
  }
  ```
</Accordion>

## Common Patterns

### Authentication with Supabase

```typescript theme={null}
// middleware.ts
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'

export async function middleware(req) {
  const res = NextResponse.next()
  const supabase = createMiddlewareClient({ req, res })

  const { data: { session } } = await supabase.auth.getSession()

  if (!session && req.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', req.url))
  }

  return res
}

export const config = {
  matcher: ['/dashboard/:path*']
}
```

### Error Handling

```tsx theme={null}
// app/error.tsx
'use client'

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  return (
    <div>
      <h2>Something went wrong!</h2>
      <button onClick={reset}>Try again</button>
    </div>
  )
}
```

## Deployment

<Cards>
  <Card title="Vercel" icon="triangle">
    Zero-config deployment with automatic preview URLs
  </Card>

  <Card title="Railway" icon="train">
    Full-stack deployment with database provisioning
  </Card>
</Cards>

<Warning>
  Always use environment variables for sensitive data. Never commit `.env.local` files.
</Warning>
