Next.js Discord

Discord Forum

Cache always MISS (SSR??)

Answered
Silver posted this in #help-forum
Open in Discord
SilverOP
Hello,
i'm trying some things out in nextjs 13 with the app router but for some odd reason the api call is never cached and always shows miss
import Link from "next/link";
import React from "react";

async function getData() {
  const res = await fetch("https://random-data-api.com/api/v2/users");
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.

  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error("Failed to fetch data");
  }

  return res.json();
}

async function foo() {
  const data = await getData();

  return (
    <div>
      {data.uid} <Link href={"/"}>go back to home</Link>
    </div>
  );
}

export default foo;

this is the code i'm using i might be doing something wrong but it came from the docs so I assume i'm right??
Answered by Giant panda
Have you tried the force-cache option?

await fetch(url, {
cache: 'force-cache',
})

You can check more here:
https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options

You might need to consider adding a tag so that you can re-validate that data if needed, or add a custom duration for the cache. You can do these like so:

await fetch(url, {
cache: 'force-cache',
next: {
tags: ['inventory'], //tag
revalidate: 60 //time e.g. 60 seconds
}
})
View full answer

8 Replies

SilverOP
Apparently cache only works when it is build for production?
SilverOP
huh and now it is working in dev mode
SilverOP
and now its broken again
SilverOP
and now it works again i'm so confused
:kekw:
Giant panda
Have you tried the force-cache option?

await fetch(url, {
cache: 'force-cache',
})

You can check more here:
https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options

You might need to consider adding a tag so that you can re-validate that data if needed, or add a custom duration for the cache. You can do these like so:

await fetch(url, {
cache: 'force-cache',
next: {
tags: ['inventory'], //tag
revalidate: 60 //time e.g. 60 seconds
}
})
Answer