# Next.js API Reference

Complete API documentation for Next.js App Router.

## Navigation

### Client Hooks

**useRouter**
```typescript
import { useRouter } from 'next/navigation';

const router = useRouter();
router.push('/about');     // Navigate
router.replace('/login');   // Replace history
router.refresh();            // Refresh data
router.back();               // Go back
```

**usePathname**
```typescript
import { usePathname } from 'next/navigation';

const pathname = usePathname(); // '/about'
```

**useSearchParams**
```typescript
import { useSearchParams } from 'next/navigation';

const params = useSearchParams();
const q = params.get('q');
```

**useParams**
```typescript
import { useParams } from 'next/navigation';

const params = useParams<{ slug: string }>();
```

### Server Functions

**redirect**
```typescript
import { redirect } from 'next/navigation';

export default async function Page() {
  const user = await getUser();
  if (!user) redirect('/login');
  return <div>{user.name}</div>;
}
```

**notFound**
```typescript
import { notFound } from 'next/navigation';

export default async function Post({ params }) {
  const post = await getPost(params.id);
  if (!post) notFound();
  return <article>{post.content}</article>;
}
```

**forbidden & unauthorized**
```typescript
import { forbidden, unauthorized } from 'next/navigation';

if (!user) unauthorized();
if (!user.isAdmin) forbidden();
```

## Components

### Link

```typescript
import Link from 'next/link';

<Link href="/about">About</Link>
<Link href="/dashboard" scroll={false}>Dashboard</Link>
<Link href="/heavy" prefetch={false}>Heavy Page</Link>
```

### Image

```typescript
import Image from 'next/image';

<Image
  src="/photo.jpg"
  alt="Photo"
  width={800}
  height={600}
  priority              // Above-the-fold
  placeholder="blur"
  quality={85}
/>
```

### Script

```typescript
import Script from 'next/script';

<Script
  src="https://example.com/script.js"
  strategy="afterInteractive"
  onReady={() => console.log('Ready')}
/>
```

### Form

```typescript
import Form from 'next/form';

<Form action={async (formData) => {
  'use server';
  await processForm(formData);
  redirect('/success');
}}>
  <input name="title" />
  <button type="submit">Submit</button>
</Form>
```

## Server Utilities

### NextRequest & NextResponse

```typescript
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const q = searchParams.get('q');
  
  return NextResponse.json({ data: 'value', query: q });
}

export async function POST(request: NextRequest) {
  const body = await request.json();
  return NextResponse.json(body, { status: 201 });
}
```

### Headers & Cookies

```typescript
import { headers, cookies } from 'next/headers';

export default async function Page() {
  const headersList = await headers();
  const userAgent = headersList.get('user-agent');
  
  const cookieStore = await cookies();
  const token = cookieStore.get('token');
  
  return <div>{userAgent}</div>;
}
```

## Caching & Revalidation

### Fetch Options

```typescript
// Time-based revalidation (ISR)
const res = await fetch('https://api.example.com/data', {
  next: { revalidate: 3600 }
});

// Tag-based revalidation
const posts = await fetch('https://api.example.com/posts', {
  next: { tags: ['posts'] }
});

// Force no cache
const res = await fetch('https://api.example.com/data', {
  cache: 'no-store'
});
```

### Revalidation Functions

```typescript
import { revalidatePath, revalidateTag } from 'next/cache';

// Revalidate by path
revalidatePath('/posts');

// Revalidate by tag
revalidateTag('posts');
```

### Cache Control

```typescript
import { unstable_cache, unstable_noStore } from 'next/cache';

// Cache expensive operation
const getCachedData = unstable_cache(
  async () => await db.query(),
  ['users'],
  { revalidate: 3600, tags: ['users'] }
);

// Force dynamic
export default async function Page() {
  unstable_noStore();
  const data = await fetchData();
  return <div>{data}</div>;
}
```

## Route Segment Config

```typescript
// Rendering behavior
export const dynamic = 'force-dynamic'; // or 'force-static', 'auto'

// Revalidation
export const revalidate = 60; // seconds

// Runtime
export const runtime = 'nodejs' | 'edge';

// Duration limit
export const maxDuration = 60; // seconds
```

## Configuration

### next.config.js

```typescript
import type { NextConfig } from 'next';

const config: NextConfig = {
  reactStrictMode: true,
  images: {
    domains: ['example.com'],
  },
  redirects: async () => [
    { source: '/old', destination: '/new', permanent: true },
  ],
};

export default config;
```

### Metadata

```typescript
import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Page Title',
  description: 'Description',
  openGraph: {
    title: 'OG Title',
    images: ['/og-image.jpg'],
  },
};
```

## Font Optimization

### Google Fonts

```typescript
import { Inter } from 'next/font/google';

const inter = Inter({
  subsets: ['latin'],
  variable: '--font-inter',
});

export default function Layout({ children }) {
  return <html className={inter.variable}>{children}</html>;
}
```

### Local Fonts

```typescript
import localFont from 'next/font/local';

const myFont = localFont({
  src: './fonts/my-font.woff2',
  variable: '--font-custom',
  display: 'swap',
});
```

## CLI Commands

```bash
# Development
next dev                  # Start dev server
next dev --turbo          # With Turbopack

# Production
next build                # Build for production
next start                # Start production server

# Other
next lint                 # Run linter
next info                 # System info
```

## Complete Type Interfaces

### Link Props
```typescript
interface LinkProps {
  href: string | UrlObject;
  replace?: boolean;
  scroll?: boolean;
  prefetch?: boolean | null;
  locale?: string | false;
}
```

### Image Props
```typescript
interface ImageProps {
  src: string | StaticImageData;
  alt: string;
  width?: number;
  height?: number;
  fill?: boolean;
  sizes?: string;
  quality?: number;
  priority?: boolean;
  placeholder?: 'blur' | 'empty';
  blurDataURL?: string;
}
```

### Script Props
```typescript
interface ScriptProps {
  src?: string;
  strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload' | 'worker';
  onLoad?: () => void;
  onReady?: () => void;
  onError?: (e: any) => void;
  id?: string;
}
```

### Navigation Options
```typescript
interface NavigateOptions {
  scroll?: boolean;
}

interface PrefetchOptions {
  kind?: 'auto' | 'full' | 'temporary';
}
```

