---
description: Authentication: How to implement Clerk auth patterns and use our reusable components
globs: app/**/*.tsx, components/**/*.tsx
alwaysApply: false
---

# Clerk Authentication Patterns

## Description
This rule documents the standard patterns for implementing authentication with Clerk in our application, including reusable components and best practices.

## Server-Side Authentication

### Server Components
```typescript
import { auth } from "@clerk/nextjs/server"

export default async function ServerComponent() {
  const { userId } = await auth()
  
  // Use userId to conditionally render content
  if (!userId) {
    return <SignInPrompt />
  }
  
  return <AuthenticatedContent />
}
```

### Server Actions
```typescript
import { auth } from "@clerk/nextjs/server"

export async function serverAction() {
  const { userId } = await auth()
  if (!userId) {
    throw new Error("Unauthorized")
  }
  // Proceed with authenticated action
}
```

## Client-Side Authentication

### Client Components
```typescript
"use client"
import { useUser, SignInButton } from "@clerk/nextjs"

export function ClientComponent() {
  const { isSignedIn, isLoaded, user } = useUser()
  
  if (!isLoaded) return <LoadingState />
  if (!isSignedIn) return <SignInPrompt />
  
  return <AuthenticatedContent />
}
```

## Reusable Components

### SignInButton
The `SignInButton` component from Clerk should be used with our custom Button component:
```typescript
import { SignInButton } from "@clerk/nextjs"
import { Button } from "@/components/ui/button"

<SignInButton mode="modal">
  <Button size="lg">Sign in to Continue</Button>
</SignInButton>
```

### Auth Buttons
For navigation/header auth controls, use our `AuthButtons` component:
```typescript
import AuthButtons from "@/components/nav/auth-buttons"

<AuthButtons />
```

### Sign In Prompt Card
For gating features behind authentication, use this pattern:
```typescript
<Card>
  <CardContent className="flex flex-col items-center gap-6 py-16">
    <div className="text-center space-y-2">
      <h2 className="text-2xl font-semibold">Sign in to Continue</h2>
      <p className="text-muted-foreground">Create an account or sign in to access this feature</p>
    </div>
    <SignInButton mode="modal">
      <Button size="lg">Sign in to Continue</Button>
    </SignInButton>
  </CardContent>
</Card>
```

## Best Practices

1. **Server vs Client Auth**
   - Use `auth()` from "@clerk/nextjs/server" in server components
   - Use `useUser()` hook in client components
   - Never mix server and client auth methods

2. **Modal vs Redirect**
   - Use `mode="modal"` for inline feature gating
   - Use redirect mode for full-page auth requirements

3. **Loading States**
   - Always handle `isLoaded` state in client components
   - Provide appropriate loading UI to prevent flashing

4. **Error Handling**
   - Catch and handle authentication errors gracefully
   - Provide clear feedback when authentication is required

5. **Protected Routes**
   - Use middleware for route protection when needed
   - Implement proper redirects for unauthenticated users

## Examples

### Feature Gating
```typescript
{userId ? (
  <ProtectedFeature />
) : (
  <Card>
    <CardContent className="flex flex-col items-center gap-6 py-16">
      <div className="text-center space-y-2">
        <h2 className="text-2xl font-semibold">Sign in to Access</h2>
        <p className="text-muted-foreground">
          Create an account or sign in to continue
        </p>
      </div>
      <SignInButton mode="modal">
        <Button size="lg">Sign in to Continue</Button>
      </SignInButton>
    </CardContent>
  </Card>
)}
```

### Protected API Route
```typescript
import { auth } from "@clerk/nextjs/server"
import { NextResponse } from "next/server"

export async function POST(request: Request) {
  const { userId } = await auth()
  
  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }
  
  // Handle authenticated request
}
``` 