| 1 | # Data Patterns |
| 2 | |
| 3 | Choose the right data fetching pattern for each use case. |
| 4 | |
| 5 | ## Decision Tree |
| 6 | |
| 7 | ``` |
| 8 | Need to fetch data? |
| 9 | ├── From a Server Component? |
| 10 | │ └── Use: Fetch directly (no API needed) |
| 11 | │ |
| 12 | ├── From a Client Component? |
| 13 | │ ├── Is it a mutation (POST/PUT/DELETE)? |
| 14 | │ │ └── Use: Server Action |
| 15 | │ └── Is it a read (GET)? |
| 16 | │ └── Use: Route Handler OR pass from Server Component |
| 17 | │ |
| 18 | ├── Need external API access (webhooks, third parties)? |
| 19 | │ └── Use: Route Handler |
| 20 | │ |
| 21 | └── Need REST API for mobile app / external clients? |
| 22 | └── Use: Route Handler |
| 23 | ``` |
| 24 | |
| 25 | ## Pattern 1: Server Components (Preferred for Reads) |
| 26 | |
| 27 | Fetch data directly in Server Components - no API layer needed. |
| 28 | |
| 29 | ```tsx |
| 30 | // app/users/page.tsx |
| 31 | async function UsersPage() |
| 32 | // Direct database access - no API round-trip |
| 33 | const users = |
| 34 | |
| 35 | // Or fetch from external API |
| 36 | const posts = |
| 37 | |
| 38 | return ( |
| 39 | <ul> |
| 40 | {users.map(( |
| 41 | <li key={ |
| 42 | ))} |
| 43 | </ul> |
| 44 | ); |
| 45 | } |
| 46 | ``` |
| 47 | |
| 48 | **Benefits**: |
| 49 | |
| 50 | - No API to maintain |
| 51 | - No client-server waterfall |
| 52 | - Secrets stay on server |
| 53 | - Direct database access |
| 54 | |
| 55 | ## Pattern 2: Server Actions (Preferred for Mutations) |
| 56 | |
| 57 | Server Actions are the recommended way to handle mutations. |
| 58 | |
| 59 | ```tsx |
| 60 | // app/actions.ts |
| 61 | "use server"; |
| 62 | |
| 63 | import { revalidatePath } |
| 64 | |
| 65 | export async function createPost |
| 66 | const title = |
| 67 | |
| 68 | await db.post |
| 69 | |
| 70 | revalidatePath("/posts"); |
| 71 | } |
| 72 | |
| 73 | export async function deletePost |
| 74 | await db.post |
| 75 | |
| 76 | revalidateTag("posts"); |
| 77 | } |
| 78 | ``` |
| 79 | |
| 80 | ```tsx |
| 81 | // app/posts/new/page.tsx |
| 82 | import { createPost } |
| 83 | |
| 84 | export default function NewPost |
| 85 | return ( |
| 86 | <form action={ |
| 87 | <input name=" |
| 88 | <button type=" |
| 89 | </form> |
| 90 | ); |
| 91 | } |
| 92 | ``` |
| 93 | |
| 94 | **Benefits**: |
| 95 | |
| 96 | - End-to-end type safety |
| 97 | - Progressive enhancement (works without JS) |
| 98 | - Automatic request handling |
| 99 | - Integrated with React transitions |
| 100 | |
| 101 | **Constraints**: |
| 102 | |
| 103 | - POST only (no GET caching semantics) |
| 104 | - Internal use only (no external access) |
| 105 | - Cannot return non-serializable data |
| 106 | |
| 107 | ## Pattern 3: Route Handlers (APIs) |
| 108 | |
| 109 | Use Route Handlers when you need a REST API. |
| 110 | |
| 111 | ```tsx |
| 112 | // app/api/posts/route.ts |
| 113 | import { NextRequest, NextResponse |
| 114 | |
| 115 | // GET is cacheable |
| 116 | export async function GET |
| 117 | const posts = |
| 118 | return NextResponse.json |
| 119 | } |
| 120 | |
| 121 | // POST for mutations |
| 122 | export async function POST |
| 123 | const body = |
| 124 | const post = |
| 125 | return NextResponse.json |
| 126 | } |
| 127 | ``` |
| 128 | |
| 129 | **When to use**: |
| 130 | |
| 131 | - External API access (mobile apps, third parties) |
| 132 | - Webhooks from external services |
| 133 | - GET endpoints that need HTTP caching |
| 134 | - OpenAPI/Swagger documentation needed |
| 135 | |
| 136 | **When NOT to use**: |
| 137 | |
| 138 | - Internal data fetching (use Server Components) |
| 139 | - Mutations from your UI (use Server Actions) |
| 140 | |
| 141 | ## Avoiding Data Waterfalls |
| 142 | |
| 143 | ### Problem: Sequential Fetches |
| 144 | |
| 145 | ```tsx |
| 146 | // Bad: Sequential waterfalls |
| 147 | async function Dashboard() |
| 148 | const user = |
| 149 | const posts = |
| 150 | const comments = |
| 151 | |
| 152 | return <div>... |
| 153 | } |
| 154 | ``` |
| 155 | |
| 156 | ### Solution 1: Parallel Fetching with Promise.all |
| 157 | |
| 158 | ```tsx |
| 159 | // Good: Parallel fetching |
| 160 | async function Dashboard() |
| 161 | const [user, |
| 162 | |
| 163 | return <div>... |
| 164 | } |
| 165 | ``` |
| 166 | |
| 167 | ### Solution 2: Streaming with Suspense |
| 168 | |
| 169 | ```tsx |
| 170 | // Good: Show content progressively |
| 171 | import { Suspense } |
| 172 | |
| 173 | async function Dashboard() |
| 174 | return ( |
| 175 | <div> |
| 176 | <Suspense fallback= |
| 177 | <UserSection /> |
| 178 | </Suspense> |
| 179 | <Suspense fallback= |
| 180 | <PostsSection /> |
| 181 | </Suspense> |
| 182 | </div> |
| 183 | ); |
| 184 | } |
| 185 | |
| 186 | async function UserSection() |
| 187 | const user = |
| 188 | return <div>{ |
| 189 | } |
| 190 | |
| 191 | async function PostsSection() |
| 192 | const posts = |
| 193 | return <PostList |
| 194 | } |
| 195 | ``` |
| 196 | |
| 197 | ### Solution 3: Preload Pattern |
| 198 | |
| 199 | ```tsx |
| 200 | // lib/data.ts |
| 201 | import { cache } |
| 202 | |
| 203 | export const getUser = |
| 204 | return db.user |
| 205 | }); |
| 206 | |
| 207 | export const preloadUser = |
| 208 | void getUser(id) |
| 209 | }; |
| 210 | ``` |
| 211 | |
| 212 | ```tsx |
| 213 | // app/user/[id]/page.tsx |
| 214 | import { getUser, preloadUser |
| 215 | |
| 216 | export default async function |
| 217 | const { id |
| 218 | |
| 219 | // Start fetching early |
| 220 | preloadUser(id); |
| 221 | |
| 222 | // Do other work... |
| 223 | |
| 224 | // Data likely ready by now |
| 225 | const user = |
| 226 | return <div>{ |
| 227 | } |
| 228 | ``` |
| 229 | |
| 230 | ## Client Component Data Fetching |
| 231 | |
| 232 | When Client Components need data: |
| 233 | |
| 234 | ### Option 1: Pass from Server Component (Preferred) |
| 235 | |
| 236 | ```tsx |
| 237 | // Server Component |
| 238 | async function Page() |
| 239 | const data = |
| 240 | return <ClientComponent |
| 241 | } |
| 242 | |
| 243 | // Client Component |
| 244 | ("use client"); |
| 245 | function ClientComponent({ initialData |
| 246 | const [data, |
| 247 | // ... |
| 248 | } |
| 249 | ``` |
| 250 | |
| 251 | ### Option 2: Fetch on Mount (When Necessary) |
| 252 | |
| 253 | ```tsx |
| 254 | "use client"; |
| 255 | import { useEffect, useState |
| 256 | |
| 257 | function ClientComponent() { |
| 258 | const [data, |
| 259 | |
| 260 | useEffect(() => |
| 261 | fetch("/api/data") |
| 262 | .then((r) |
| 263 | .then(setData); |
| 264 | }, []); |
| 265 | |
| 266 | if (!data) |
| 267 | return <div>{ |
| 268 | } |
| 269 | ``` |
| 270 | |
| 271 | ### Option 3: Server Action for Reads (Works But Not Ideal) |
| 272 | |
| 273 | Server Actions can be called from Client Components for reads, but this is not their intended purpose: |
| 274 | |
| 275 | ```tsx |
| 276 | "use client"; |
| 277 | import { getData } |
| 278 | import { useEffect, useState |
| 279 | |
| 280 | function ClientComponent() { |
| 281 | const [data, |
| 282 | |
| 283 | useEffect(() => |
| 284 | getData().then(setData |
| 285 | }, []); |
| 286 | |
| 287 | return <div>{ |
| 288 | } |
| 289 | ``` |
| 290 | |
| 291 | **Note**: Server Actions always use POST, so no HTTP caching. Prefer Route Handlers for cacheable reads. |
| 292 | |
| 293 | ## Quick Reference |
| 294 | |
| 295 | | Pattern | Use Case | HTTP Method | Caching | |
| 296 | | ---------------------- | --------------------------- | |
| 297 | | Server Component fetch | Internal reads | Any | Full Next.js caching | |
| 298 | | Server Action | Mutations, form submissions | POST only | No | |
| 299 | | Route Handler | External APIs, webhooks | Any | GET can be cached | |
| 300 | | Client fetch to API | Client-side reads | Any | HTTP cache headers | |