Next.js API Route Data Cache Issue on Vercel Deployment
In a Next.js v13.2 application, an API endpoint fetching data from a database encounters a peculiar behavior after deployment on Vercel. The same response is consistently returned, suggesting a caching issue.
Root Cause:
By default, Next.js caches all fetched data in API Routes and Server Components on production. When a request is made to the API route, the cached data is served instead of fetching new data from the database.
Solutions:
1. Per-Query Cache Control with fetch()
If using the fetch() API, you can override the default caching behavior by specifying the revalidate or cache options:
cache: Explicitly sets the cache behavior, options include:
Example:
<code class="js">fetch('https://...', { next: { revalidate: 10 } }); // OR fetch('https://...', { cache: 'no-store' });</code>
2. Route Segment Config for Generalized Caching
If you're not using fetch() or need to control caching at the route segment level, use Route Segment Config:
Example:
<code class="js">// layout.js OR page.js OR route.js import prisma from "./lib/prisma"; export const dynamic = "force-dynamic"; async function getPosts() { const posts = await prisma.post.findMany(); return posts; } export default async function Page() { const posts = await getPosts(); // ... }</code>
The above is the detailed content of Why is my Next.js API Route returning cached data on Vercel deployment?. For more information, please follow other related articles on the PHP Chinese website!