home / skills / amnadtaowsoam / cerebraskills / nextjs-patterns
This skill helps you master Next.js 14+ App Router features like Server Components, Streaming, and Server Actions to build fast, scalable apps.
npx playbooks add skill amnadtaowsoam/cerebraskills --skill nextjs-patternsReview the files below or copy the command above to add this skill to your agents.
---
name: Next.js 14+ App Router Patterns
description: Expert-level framework for building modern React applications using Next.js 14+ App Router with Server Components, Streaming, Server Actions, and improved data fetching capabilities.
---
# Next.js 14+ App Router Patterns
## Overview
Next.js 14+ App Router is a powerful React framework with features including Server Components, Streaming, Server Actions, and improved data fetching. The App Router uses file-based routing and nested layouts, making it easier to build complex applications. Key features include Server Components that reduce JavaScript bundles, Streaming for progressive rendering, Server Actions for server-side functions, and improved caching strategies for optimal performance.
## Why This Matters
- **Reduces Time-to-Market**: Next.js reduces development time by 30-40%
- **Improves Performance**: Server Components and Streaming enhance performance
- **Lowers Infrastructure Cost**: Edge runtime and caching reduce operational costs
- **Enhances SEO**: Server-side rendering improves search engine optimization
- **Improves Developer Experience**: Powerful features increase developer productivity
---
## Core Concepts
### 1. File-Based Routing
Directory-based routing:
- **app/**: App Router directory containing routes
- **page.tsx**: Route page component
- **layout.tsx**: Layout component wrapping child routes
- **loading.tsx**: Loading UI for Suspense boundaries
- **error.tsx**: Error boundary UI
- **not-found.tsx**: 404 page
- **route.ts**: API route handler
### 2. Server Components vs Client Components
Component execution models:
- **Server Components (Default)**: Render on server, no JavaScript shipped to client
- **Client Components**: Render on client, can use hooks and browser APIs
- **Mixed Architecture**: Combining server and client components for optimal performance
- **Component Composition**: Server components can import and use client components
### 3. Data Fetching
Flexible data fetching patterns:
- **Server Components**: Direct database/API access in server components
- **fetch() API**: Built-in caching and revalidation
- **Server Actions**: Server-side functions called from client components
- **Streaming**: Progressive rendering with Suspense
- **Caching**: Force-cache, no-store, and revalidate options
### 4. Route Handlers
API endpoints:
- **Route Handlers**: API routes in the app directory
- **HTTP Methods**: Support for GET, POST, PUT, DELETE, PATCH
- **Dynamic Routes**: Dynamic route parameters
- **Middleware**: Request/response interception
- **CORS**: Cross-Origin Resource Sharing support
### 5. Server Actions
Server-side mutations:
- **Form Handling**: Server actions for form submissions
- **Mutations**: Database mutations from client components
- **Validation**: Server-side validation with Zod
- **Revalidation**: Cache invalidation after mutations
- **Progressive Enhancement**: Work without JavaScript
### 6. Streaming and Suspense
Progressive rendering:
- **Suspense**: Async component boundaries
- **Streaming**: Progressive HTML and data delivery
- **Loading States**: Loading UI components
- **Error Boundaries**: Error handling
- **Progressive Enhancement**: Graceful degradation
### 7. Caching Strategies
Optimization through caching:
- **force-cache**: Default caching strategy
- **no-store**: Always fetch fresh data
- **revalidate**: Time-based revalidation
- **on-demand**: Manual cache revalidation
- **Tags**: Tag-based cache invalidation
## Quick Start
1. **Initialize Project**: Create Next.js project with App Router
2. **Setup TypeScript**: Configure TypeScript with strict mode
3. **Create Layout**: Build root layout with theme provider
4. **Build Pages**: Create page components using Server Components
5. **Add Client Components**: Use Client Components for interactivity
6. **Implement Data Fetching**: Fetch data in Server Components
7. **Add Streaming**: Implement Suspense for progressive rendering
8. **Setup API Routes**: Create route handlers for API endpoints
9. **Add Server Actions**: Implement server actions for mutations
10. **Configure Caching**: Set up appropriate caching strategies
```typescript
// app/layout.tsx - Root Layout
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'My App',
description: 'A Next.js application',
}
export default function RootLayout({
children
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
)
}
```
## Production Checklist
- [ ] App Router directory structure configured
- [ ] Root layout with theme provider implemented
- [ ] TypeScript configuration with strict mode
- [ ] Server Components used by default
- [ ] Client Components marked with 'use client'
- [ ] Data fetching with appropriate caching
- [ ] Streaming with Suspense boundaries
- [ ] Loading states implemented
- [ ] Error boundaries configured
- [ ] API routes with proper HTTP methods
- [ ] Server Actions for mutations
- [ ] Caching strategies configured
- [ ] Cache revalidation implemented
- [ ] Middleware for authentication/authorization
- [ ] Security headers configured
- [ ] Performance optimized (bundle size, Core Web Vitals)
- [ ] Accessibility verified (keyboard navigation, screen readers)
- [ ] SEO optimized (metadata, structured data)
## Anti-patterns
1. **Overusing Client Components**: Using Client Components unnecessarily increases bundle size
2. **Poor Caching**: Not using appropriate caching strategies causes performance issues
3. **Ignoring SEO**: Not optimizing for server-side rendering hurts SEO
4. **Security Issues**: Not implementing security measures exposes vulnerabilities
5. **Performance Issues**: Not optimizing bundle size and rendering causes slow load times
6. **Accessibility Problems**: Not considering accessibility limits user base
7. **Complex Data Fetching**: Overly complex data fetching logic is hard to maintain
8. **Missing Error Handling**: Not implementing proper error handling causes poor UX
9. **No Caching Strategy**: Not planning caching leads to performance problems
10. **Poor Routing Structure**: Disorganized directory structure makes maintenance difficult
## Integration Points
- **React**: Core React library for components and hooks
- **TypeScript**: Type safety and interfaces
- **Tailwind CSS**: Styling framework
- **Zod**: Schema validation
- **Prisma**: Database ORM
- **Vercel**: Deployment platform
- [`react-best-practices`](../react-best-practices/SKILL.md) for React patterns
- [`form-handling`](../form-handling/SKILL.md) for form patterns
- [`api-design`](../../01-foundations/api-design/SKILL.md) for API design
- [`error-handling`](../../03-backend-api/error-handling/SKILL.md) for error handling
## Further Reading
- [Next.js Documentation](https://nextjs.org/docs) - Official Next.js documentation
- [App Router](https://nextjs.org/docs/app) - App Router guide
- [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) - Server Components guide
- [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations) - Server Actions guide
- [Data Fetching](https://nextjs.org/docs/app/building-your-application/data-fetching) - Data fetching patterns
- [Streaming](https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming) - Streaming and Suspense
- [Caching](https://nextjs.org/docs/app/building-your-application/caching) - Caching strategies
- [Web Vitals](https://web.dev/vitals/) - Core Web Vitals performance metrics
This skill is an expert-level guide for building modern React applications with Next.js 14+ App Router, focused on Server Components, Streaming, Server Actions, and advanced data fetching. It distills architecture patterns, routing conventions, and production-ready practices to help teams ship faster with better performance and lower operational cost.
It describes the App Router file conventions (app/, page.tsx, layout.tsx, route.ts, etc.), the Server vs Client component model, and data flows for server-rendering, streaming, and server-side mutations. The guide explains caching options, route handlers, and how to compose server and client code to minimize client JS while enabling interactivity via Server Actions.
When should I use Server Actions instead of client-side POST requests?
Use Server Actions for secure mutations that require server-side access, validation, or direct DB calls; they reduce client-to-server plumbing and can progressively enhance UX when JS is available.
How do I decide between force-cache, no-store, and revalidate?
Pick force-cache for static or rarely-changing assets, no-store for sensitive or real-time data, and revalidate when you can tolerate a TTL and want efficient caching with periodic refreshes.