skip to Main Content

I’m using NextJS 14.x, and have a simple /dashboard/page.tsx where I fetch data from an API. I would expect that when I change the message data I would be getting the updated response. Even if I am fetching data from a remote URL (different server) the data still appears to be cached by NextJS which makes fetching data that changes impossible.

async function fetchdetails() {
  const response = await fetch(
    "http://localhost:3000/api/public"
  );
  if (response.ok) {
    const responseBody = await response.json();
   
    console.log(responseBody);
    return responseBody;
  }
}

The API is under the /api/public folder (route.ts)

const data = {
  "message": "hello world!" 
}

export async function GET() {
  return NextResponse.json(data)
}

What is the right strategy to make sure the data is never cached by the app?

2

Answers


  1. Chosen as BEST ANSWER

    I'm not sure if this is the most efficient way (versus a config) but adding noStore() to the fetch method did work.

    import { unstable_noStore as noStore } from 'next/cache';
    
    async function fetchdetails() {
      noStore();
      const response = await fetch(
        "http://localhost:3000/api/public"
      );
      if (response.ok) {
        const responseBody = await response.json();
       
        console.log(responseBody);
        return responseBody;
      }
    }
    

  2. By default, NextJs always cache GET method. If you want opt-out caching, your API route need to use one of below:

    1. Using the Request object with the GET method. Read more Opting out of caching
    const data = {
      "message": "hello world!" }
    
    export async function GET(request: Request) {
      return NextResponse.json(data)
    }
    
    1. Opt-out caching entire route, by using Route Segment Config
    const data = {
      "message": "hello world!" }
    
    export const dynamic = 'force-dynamic'
    
    export async function GET() {
      return NextResponse.json(data)
    }
    

    If you want more granular caching strategy, you can put { cache: 'no-store' } in fetch, read more Caching in Next.js.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search