# Next.js Production Apps: Server Components and API Routes

Next.js has become my framework of choice for building production-ready full-stack applications. Here's how I leverage its powerful features.

## Why Next.js?

**Complete Full-Stack Solution**

- Server and client components
- Built-in API routes
- Automatic code splitting
- Optimized image handling
- SEO-friendly by default

## Server Components (App Router)

```tsx
// app/page.tsx
import { getProducts } from '@/lib/data';

export default async function HomePage() {
  const products = await getProducts();

  return (
    <main>
      <h1>Products</h1>
      {products.map(product => (
        <ProductCard key={product.id} product={product} />
      ))}
    </main>
  );
}
```

## API Routes

```ts
// app/api/products/route.ts
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET() {
  try {
    const products = await db.product.findMany();
    return NextResponse.json(products);
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to fetch products' },
      { status: 500 }
    );
  }
}

export async function POST(request: Request) {
  const body = await request.json();
  const product = await db.product.create({ data: body });
  return NextResponse.json(product);
}
```

## Data Fetching Patterns

```ts
// Server Component - Direct database access
async function getUser(id: string) {
  const user = await db.user.findUnique({ where: { id } });
  return user;
}

// With caching
import { unstable_cache } from 'next/cache';

const getCachedProducts = unstable_cache(
  async () => db.product.findMany(),
  ['products'],
  { revalidate: 3600 }
);
```

## My Production Setup

**Performance**
- Image optimization with next/image
- Font optimization
- Bundle analyzer

**SEO**
- Metadata API
- Sitemap generation
- robots.txt

**Developer Experience**
- TypeScript throughout
- ESLint & Prettier
- Tailwind CSS

Next.js simplifies full-stack development while maintaining excellent performance and SEO. The App Router and Server Components have transformed how I build web applications.
