Next.js App Router: The Complete Guide

App Router Fundamentals

The App Router is Next.js's file-system based router with built-in support for layouts, server components, streaming, and more.

File-System Routing

app/
โ”œโ”€โ”€ layout.tsx          # Root layout (required)
โ”œโ”€โ”€ page.tsx            # Home page (/)
โ”œโ”€โ”€ about/
โ”‚   โ””โ”€โ”€ page.tsx        # About page (/about)
โ”œโ”€โ”€ blog/
โ”‚   โ”œโ”€โ”€ page.tsx        # Blog list (/blog)
โ”‚   โ””โ”€โ”€ [slug]/
โ”‚       โ””โ”€โ”€ page.tsx    # Blog post (/blog/my-post)
โ”œโ”€โ”€ (marketing)/        # Route group (no URL impact)
โ”‚   โ”œโ”€โ”€ layout.tsx      # Marketing pages layout
โ”‚   โ”œโ”€โ”€ pricing/
โ”‚   โ”‚   โ””โ”€โ”€ page.tsx    # /pricing
โ”‚   โ””โ”€โ”€ features/
โ”‚       โ””โ”€โ”€ page.tsx    # /features
โ””โ”€โ”€ @modal/             # Parallel route for modals
    โ””โ”€โ”€ login/
        โ””โ”€โ”€ page.tsx

Layouts and Templates

// app/layout.tsx - Root layout
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    
      
        
{children}
); } // app/dashboard/layout.tsx - Nested layout export default function DashboardLayout({ children, }: { children: React.ReactNode; }) { return (
{children}
); } // app/template.tsx - Re-renders on navigation export default function Template({ children }: { children: React.ReactNode }) { return (
{children}
); }

Loading UI and Streaming

// app/dashboard/loading.tsx
export default function Loading() {
  return (
    
); } // Streaming with Suspense import { Suspense } from 'react'; async function DashboardPage() { return (

Dashboard

{/* These components stream in as they resolve */} }> }> }>
); } // Each component can fetch independently async function Stats() { const stats = await fetchStats(); // No loading state blocking return ; }

Error Handling

// app/dashboard/error.tsx
'use client';

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    

Something went wrong!

{error.message}

); } // app/not-found.tsx export default function NotFound() { return (

404 - Page Not Found

Go home
); }

Data Fetching

// Server Component - Direct data access
async function ProductsPage() {
  // This runs on the server
  const products = await db.product.findMany();
  
  return (
    
    {products.map(product => (
  • {product.name}
  • ))}
); } // Caching and revalidation async function Posts() { // Cached indefinitely (default) const posts = await fetch('https://api.example.com/posts'); // Revalidate every hour const news = await fetch('https://api.example.com/news', { next: { revalidate: 3600 } }); // No caching const live = await fetch('https://api.example.com/live', { cache: 'no-store' }); return (...); }

Server Actions

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

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';

export async function createPost(formData: FormData) {
  const title = formData.get('title') as string;
  const content = formData.get('content') as string;
  
  // Validation
  if (!title || !content) {
    return { error: 'Title and content required' };
  }
  
  // Create in database
  const post = await db.post.create({
    data: { title, content }
  });
  
  // Revalidate and redirect
  revalidatePath('/posts');
  redirect(`/posts/${post.id}`);
}

// Using in form
export default function NewPostForm() {
  return (
    
); } // With useFormState for handling errors 'use client'; import { useFormState } from 'react-dom'; import { createPost } from './actions'; export function PostForm() { const [state, formAction] = useFormState(createPost, null); return ( {state?.error &&

{state.error}

}
); }

Middleware

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  // Check authentication
  const token = request.cookies.get('token');
  
  if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  
  // Add headers
  const response = NextResponse.next();
  response.headers.set('x-request-id', crypto.randomUUID());
  
  return response;
}

export const config = {
  matcher: ['/dashboard/:path*', '/api/:path*']
};

Conclusion

The App Router brings React Server Components to Next.js with file-based routing, layouts, and streaming. Embrace server-first rendering for better performance and simpler code.

๐Ÿ“šTechnical Insights & Industry Trends

Insights & Knowledge Hub

Explore in-depth articles on software development, digital transformation, and emerging technologies. Learn from real-world experience.

Browse by Topic

๐Ÿ…ฐ๏ธ
ArchitectureJan 2024

Why Angular SSR Beats React for SEO in 2024

A comprehensive comparison of server-side rendering implementations and their impact on search engine optimization, performance, and user experience.

๐Ÿ”Œ
ArchitectureDec 2023

Microservices: When to Use and When to Avoid

Understanding the trade-offs of microservices architecture and making the right choice for your organization's scale, complexity, and team structure.

๐Ÿ—๏ธ
System ArchitectureJan 2024

Essential Design Patterns for Enterprise Systems

Master the fundamental design patterns that every software architect should know for building scalable, maintainable enterprise applications.

๐Ÿ—๏ธ
System ArchitectureJan 2024

Domain-Driven Design: A Practical Guide

Learn how to apply Domain-Driven Design principles to create software that truly reflects business requirements and scales with organizational complexity.

๐Ÿ—๏ธ
System ArchitectureDec 2023

Event-Driven Architecture: Complete Implementation Guide

Build loosely coupled, scalable systems using event-driven architecture patterns with practical examples using Kafka, RabbitMQ, and Azure Service Bus.

๐Ÿ—๏ธ
System ArchitectureDec 2023

RESTful API Design: Best Practices and Patterns

Design APIs that developers love to use. Learn REST principles, versioning strategies, error handling, and documentation best practices.

Deep Dives into Key Areas

๐Ÿ—๏ธ

System Architecture

Design patterns and architectural decisions

12 Articles
โ˜๏ธ

Cloud Computing

AWS, Azure, and cloud-native development

8 Articles
โšก

Performance

Optimization and scalability techniques

6 Articles
๐Ÿค–

AI & Machine Learning

Practical AI applications in enterprise

5 Articles
๐Ÿ”’

Security

Best practices and compliance

7 Articles
๐Ÿ“ฑ

Modern Frontend

Angular, React, and UI/UX best practices

10 Articles

Have a Project in Mind?

Let's turn your ideas into reality. Schedule a free consultation to discuss how we can help transform your business.