Search code examples
next.jsfetch-api

Fetch API Returns Empty Array in Next.js Despite Working API Endpoint


I'm using fetch() to retrieve data from my backend API in a Next.js project, but an empty array ([]) is always returned instead of the expected data. I've verified that the API is working correctly by testing it in a browser or using a tool like Postman. However, when I try to fetch the data in my Next.js component using the following code:

const BookList = async () => {
  const response = await fetch("http://localhost:3001/api/books");
  if (!response.ok) {
    throw new Error("Failed to fetch data");
  }
  const books = await response.json();
  console.log(books);
}

axios() is working perfectly but i want to use fetch() as it is recommended to use it in Next.js. What could be causing this issue, and how can I fix it to retrieve the correct data in my Next.js component?


Solution

  • The answer is to force next fetch function to force update on every request.

    Because next fetch function is basically caching every request until invalidated. In order to do that you just have to pass { cache: 'no-store' }) on the fetch options:

    For example:

    await fetch("http://localhost:3001/api/books", { cache: 'no-store' });
    

    It will force next to fetch directly to remote resource without looking for any cache.

    Here's the official documentation for more details