Next.js
/Beginner
Fetch API in Next.js
Definition
Next.js drastically extends the native Web `fetch()` API, adding caching and revalidation logic directly into the function call.
Explain Like I'm New
In React, `fetch` just grabs data. In Next.js, `fetch` is magical. It remembers the data it fetched. If 1,000 users visit your page, Next.js only runs `fetch` once, caches the result on the server, and instantly serves that cached result to all 1,000 users.
Real World Example
Fetching a list of blog posts from a headless CMS. You want it to be incredibly fast, so you use Next.js `fetch` to cache the response indefinitely.
Common Use Cases
- •Fetching remote data
- •Server-side data caching
Interactive Example
export default async function BlogFeed() { // MAGIC FETCH: This is cached automatically! // Next.js runs this ONCE at build time, and never again. const res = await fetch('https://api.mycms.com/posts'); const posts = await res.json(); return ( <ul> {posts.map(post => <li key={post.id}>{post.title}</li>)} </ul> ); }
Interview Questions
basic
- Does Next.js cache `fetch` requests by default?
intermediate
- If you are using a third-party database library (like Prisma or Mongoose) instead of `fetch`, does Next.js automatically cache it?