Home > Web Front-end > JS Tutorial > body text

Why is my Next.js API Route returning cached data on Vercel deployment?

Barbara Streisand
Release: 2024-11-02 21:11:30
Original
685 people have browsed it

Why is my Next.js API Route returning cached data on Vercel deployment?

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:

  • revalidate: Specifies the cache duration in seconds before refetching data.
  • cache: Explicitly sets the cache behavior, options include:

    • no-store: Disables caching entirely.
    • no-cache: Revalidates the cache before serving the response.
    • reload: Always fetches new data from the server.

Example:

<code class="js">fetch('https://...', { next: { revalidate: 10 } });
// OR
fetch('https://...', { cache: 'no-store' });</code>
Copy after login

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:

  • Add DYNAMIC SEGMENT: Add export const dynamic = "force-dynamic"; to your layout, page, or route file. This disables cache behavior for that segment.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!