If you're trying out the new Next.js API routes and running into problems fetching data during npm run build, you're not alone. Many developers are encountering this issue because the API route behavior has slightly changed in Next.js. Even after hours of digging through the docs, the solution might not be obvious.
The Problem
By default, Next.js tries to optimize performance with static rendering and caching. This is great for speed but can cause issues when you're fetching dynamic data that changes frequently or needs to bypass caching during build time.
The Solution
To ensure your data fetching works as expected, you need to override Next.js' default caching behavior. Add these two lines to the top of your file where you're fetching the data:
export const dynamic = "force-dynamic";
export const fetchCache = "force-no-store";
Why This Works
dynamic = "force-dynamic": Forces the page to render dynamically instead of statically.
fetchCache = "force-no-store": Disables caching for your fetch calls, ensuring you're always fetching fresh data.
Example Code
Hereβs how it looks in practice:
export const dynamic = "force-dynamic";
export const fetchCache = "force-no-store";
const getData = async () => {
const res = await fetch("https://your-api-url/api/posts");
if (!res.ok) throw new Error("Failed to fetch data");
return res.json();
};
const Blog = async () => {
const data = await getData();
return data.map((item) => <div key={item.id}>{item.title}</div>);
};
export default Blog;
Final Step
After making this change, run npm run build
again, and your problem should be solved! π
Hope this saves you hours of debugging. Thank me later π
Top comments (0)