Next.js Example

Next.js Routing

Master file-system based routing in Next.js

File Conventions

Understanding Next.js 13+ routing structure

App Router Structure

app/
├── layout.tsx      # Root layout
├── page.tsx        # Home page
├── about/
│   └── page.tsx    # About page
├── blog/
│   ├── layout.tsx  # Blog layout
│   ├── page.tsx    # Blog index
│   └── [slug]/     # Dynamic route
│       └── page.tsx
└── api/           # API routes
    └── posts/
        └── route.ts

Basic Page Component

// app/page.tsx
export default function HomePage() {
  return (
    

Welcome to Next.js

This is a basic page component.

); }

Key Points

  • Files in app/ directory define routes
  • page.tsx files are required for routes
  • layout.tsx files wrap child routes
  • Nested folders create nested routes

Dynamic Routes

Creating routes with dynamic parameters

Dynamic Route Parameters

// app/blog/[slug]/page.tsx
export default function BlogPost({ params }: { params: { slug: string } }) {
  return (
    

Post: {params.slug}

); } // Generate static params at build time export async function generateStaticParams() { const posts = await getPosts(); return posts.map((post) => ({ slug: post.slug, })); }

Catch-all Routes

// app/docs/[...slug]/page.tsx
export default function Doc({ params }: { params: { slug: string[] } }) {
  // slug will be an array of path segments
  // e.g., /docs/a/b/c → slug: ['a', 'b', 'c']
  return (
    

Documentation

Current path: {params.slug.join('/')}

); }

Key Points

  • Use [param] for dynamic segments
  • [...slug] for catch-all routes
  • Optional catch-all with [[...slug]]
  • Generate static paths at build time

Route Handlers

Creating API endpoints with Next.js

Basic Route Handler

// app/api/posts/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
  const posts = await getPosts();
  return NextResponse.json(posts);
}

export async function POST(request: Request) {
  const data = await request.json();
  const newPost = await createPost(data);
  return NextResponse.json(newPost, { status: 201 });
}

Dynamic API Routes

// app/api/posts/[id]/route.ts
import { NextResponse } from 'next/server';

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  const post = await getPost(params.id);
  
  if (!post) {
    return NextResponse.json(
      { error: 'Post not found' },
      { status: 404 }
    );
  }
  
  return NextResponse.json(post);
}

export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
) {
  await deletePost(params.id);
  return NextResponse.json({}, { status: 204 });
}

Key Points

  • Support for HTTP methods
  • Dynamic API routes with params
  • Built-in request handling
  • Response helpers with NextResponse