Back to Guides
Data

API Routes & Route Handlers

Create secure API endpoints inside your application. Handle HTTP requests, responses, and API middleware.

Prerequisites

  • Basic React knowledge (components, props, state)
  • Node.js 18+ installed
  • Familiarity with terminal/command line

1. Understanding the App Directory

The app/ directory replaces the old pages/ directory. Every folder inside app/ maps to a URL segment.

app/page.tsx
export default function Home() {
  return <h1>Welcome to Next.js</h1>;
}

2. Layouts & Nesting

Layouts wrap child routes and persist across navigations. Define a layout.tsx in any folder to create a shared UI shell.

app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

3. Dynamic Routes

Use bracket notation to create dynamic segments. Access params via the component props.

app/blog/[slug]/page.tsx
export default function BlogPost({
  params,
}: {
  params: { slug: string };
}) {
  return <h1>Post: {params.slug}</h1>;
}

Common Mistakes

Mixing `pages/` and `app/` directories for the same route
Forgetting that components in `app/` are Server Components by default
Using `useState` or `useEffect` in Server Components

Key Takeaways

  • The App Router uses file-system conventions for routing
  • Layouts persist state across navigations
  • Components are Server Components by default
  • Dynamic routes use bracket notation [param]

Related Guides