Beginner12 min

Understand why Next.js is the framework of choice for AI coding tools and how it powers modern web applications.

Introduction to Next.js

Next.js is the React framework that AI coding tools use most frequently. Understanding its fundamentals helps you work more effectively with AI-generated code.

Why AI Tools Love Next.js

When you use Lovable, Bolt.new, v0, or ask Claude Code to build a web app, you'll likely get Next.js code. Here's why:

Full-Stack in One Framework

Terminal
Traditional Stack:
├── Frontend (React)
├── Backend (Express/Node)
├── API layer (separate)
└── Database connection (separate)

Next.js Stack:
└── Next.js
    ├── React components
    ├── API routes
    ├── Server actions
    └── Database access

AI tools can generate entire applications without switching contexts.

File-Based Routing

No configuration needed—just create files:

Terminal
app/
├── page.tsx            yoursite.com/
├── about/
   └── page.tsx        yoursite.com/about
├── blog/
   ├── page.tsx        yoursite.com/blog
   └── [slug]/
       └── page.tsx    yoursite.com/blog/any-post
└── api/
    └── users/
        └── route.ts    yoursite.com/api/users

AI can reason about URLs by looking at file structure.

Built-in Optimizations

  • Image optimization: Automatic resizing and lazy loading
  • Font optimization: Google Fonts without layout shift
  • Code splitting: Only load what's needed
  • Caching: Smart defaults for performance

Next.js Versions

App Router (Next.js 13+)

The modern approach using React Server Components:

Terminal
// app/page.tsx - Server Component by default
export default async function HomePage() {
  const data = await fetchData() // Runs on server

  return (
    <main>
      <h1>Welcome</h1>
      <DataDisplay data={data} />
    </main>
  )
}

Most AI tools generate App Router code.

Pages Router (Legacy)

The original routing system:

Terminal
// pages/index.tsx
export default function HomePage({ data }) {
  return <main>{/* ... */}</main>
}

export async function getServerSideProps() {
  const data = await fetchData()
  return { props: { data } }
}

You may encounter this in older tutorials or codebases.

Key Concepts for AI Development

Server Components

React components that run on the server:

Terminal
// This runs on the server, not the browser
export default async function ProductPage({ params }) {
  // Direct database access - no API needed
  const product = await db.product.findUnique({
    where: { id: params.id }
  })

  return <ProductDetails product={product} />
}

Benefits for AI development:

  • Simpler data fetching
  • No loading states for initial data
  • Secure database access

Client Components

Components that run in the browser:

Terminal
'use client' // This directive makes it a client component

import { useState } from 'react'

export default function Counter() {
  const [count, setCount] = useState(0)

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  )
}

Needed when you use:

  • useState, useEffect, hooks
  • Browser APIs
  • Event handlers

Server Actions

Functions that run on the server, called from the client:

Terminal
// app/actions.ts
'use server'

export async function createUser(formData: FormData) {
  const name = formData.get('name')

  await db.user.create({
    data: { name: name as string }
  })

  revalidatePath('/users')
}
Terminal
// app/signup/page.tsx
import { createUser } from './actions'

export default function SignupForm() {
  return (
    <form action={createUser}>
      <input name="name" required />
      <button type="submit">Sign Up</button>
    </form>
  )
}

No API routes needed for form handling.

How AI Tools Generate Next.js

Lovable/Bolt Pattern

These tools typically generate:

Terminal
src/
├── app/
   ├── layout.tsx      # Root layout with providers
   ├── page.tsx        # Home page
   └── globals.css     # Global styles
├── components/
   ├── ui/             # shadcn/ui components
   └── ...             # Feature components
└── lib/
    └── utils.ts        # Utility functions

v0 Pattern

v0 generates components you copy into your project:

Terminal
// v0 output - a single component
export default function Component() {
  return (
    <div className="flex flex-col...">
      {/* Component code */}
    </div>
  )
}

Claude Code Pattern

Claude Code works with existing projects or creates new ones:

Terminal
# Claude Code might run:
npx create-next-app@latest my-app --typescript --tailwind --app

Then generates files based on your requests.

Working with AI-Generated Next.js

Review the Structure

When AI generates code, check:

Terminal
 Is it using App Router (app/) or Pages Router (pages/)?
 Are components in the right directories?
 Are Server/Client components correctly marked?
 Does the layout structure make sense?

Common Patterns to Recognize

Layout with Providers:

Terminal
// app/layout.tsx
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <ThemeProvider>
          <Header />
          {children}
          <Footer />
        </ThemeProvider>
      </body>
    </html>
  )
}

Dynamic Routes:

Terminal
// app/products/[id]/page.tsx
export default function ProductPage({ params }) {
  const { id } = params // 'id' comes from the URL
  // ...
}

API Routes:

Terminal
// app/api/products/route.ts
export async function GET() {
  const products = await db.product.findMany()
  return Response.json(products)
}

export async function POST(request: Request) {
  const data = await request.json()
  const product = await db.product.create({ data })
  return Response.json(product, { status: 201 })
}

Prompting AI for Next.js

Effective Prompts

Terminal
"Create a Next.js App Router page for user profiles"

"Build a dashboard layout with sidebar navigation using Next.js"

"Add an API route for handling user registration with validation"

Include Context

Terminal
"Using Next.js 14 App Router with TypeScript and Tailwind CSS,
create a blog post page that:
- Fetches post data from a Prisma database
- Has dynamic meta tags for SEO
- Includes a comment section (client component)"

Specify Patterns

Terminal
"Follow the same pattern as the products page for this new
orders page, including the same error handling and loading states"

Common Issues

"useState is not allowed in Server Components"

Add 'use client' directive:

Terminal
'use client'

import { useState } from 'react'

"Can't use hooks in async components"

Async components must be Server Components (no hooks):

Terminal
//  Won't work
export default async function Page() {
  const [state, setState] = useState() // Error!
}

//  Split into server and client parts
export default async function Page() {
  const data = await fetchData()
  return <ClientComponent initialData={data} />
}

Import Errors

Watch for client-only imports in Server Components:

Terminal
//  Error in Server Component
import { useRouter } from 'next/navigation'

//  Use in Client Component
'use client'
import { useRouter } from 'next/navigation'

Summary

  • Next.js is the most common framework AI tools generate
  • App Router uses file-based routing and Server Components
  • Server Components fetch data directly, Client Components handle interactivity
  • Server Actions replace API routes for mutations
  • Understanding these patterns helps you work with AI-generated code

Next Steps

Learn how the App Router organizes files and handles routing in the next lesson.

Mark this lesson as complete to track your progress