#Disabling API cache

6 messages · Page 1 of 1 (latest)

daring onyx
#

I have this API call on frontend:

fetch(`/api/top_friends_users`, {
      method: "GET"
    })
    .then((response) => {
      return response.json();
    })
    .then((data: { user_full_name: string; friends: string }[]) => {
      const localData = data.map(user => ({
        userFullName: user.user_full_name,
        friends: Number(user.friends)
      }));

      setTopFriendsUsers(localData);
    });

And this route.ts on backend:

export async function GET(request: NextRequest) {
  console.log('API: /top_friends_users');
  const query = 
    `
    SELECT ui.user_full_name, COUNT(r.referred_user_id) AS friends
    FROM referrals AS r JOIN user_info AS ui
        ON r.referrer_user_id = ui.user_id
    GROUP BY ui.user_full_name
    ORDER BY friends DESC
    LIMIT 100;
    `
  const result = await pool.query(query);
  const response = NextResponse.json(result.rows);
  return response;
}

And this works very fine when using dev mode, but in production mode (npm run build, and then npm run start) I don't get fresh results with each page visit, the results are cached..
I'm using Next.js v14.2.5, with pg package for PostgreSQL,
tried with this: https://nextjs.org/docs/app/api-reference/functions/fetch#optionscache

fetch(`/api/top_friends_users`, {
      method: "GET",
      cache: "no-store"
    })

But didn't work out, also tried with this on backend, but the same thing:

const response = NextResponse.json(result.rows);
response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
response.headers.set('Pragma', 'no-cache');
response.headers.set('Expires', '0');

But when I change url to this:

fetch(`/api/top_friends_users${new Date()}`, ...)

Then it works.. So I guess when url is the same Nextjs is using cached results, but I don't want that, I want to fetch from db with each page visit, once again in production mode doesn't work

API reference for the extended fetch function.

cyan mortarBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

knotty mulch
daring onyx
knotty mulch
daring onyx
#

Got it, thank you