Next.js Discord

Discord Forum

Is it okay to use useSWR with node-cache?

Answered
Eared Trogon posted this in #help-forum
Open in Discord
Eared TrogonOP
I am using useSWR for caching requests but seems it so not caching in server wide, and everytime it calls my api routes makes other requests to server. So i am using other caching layers with node cache. Is it okay to mix up these?
Answered by joulev
swr is only for client-side caching.

yes, it's completely fine to mix up them. your node-cache (or any caching stuff you bring) is on the server, completely separated from the client where swr manages the cache.
View full answer

8 Replies

swr is only for client-side caching.

yes, it's completely fine to mix up them. your node-cache (or any caching stuff you bring) is on the server, completely separated from the client where swr manages the cache.
Answer
Eared TrogonOP
Thanks. I guess i am a bit confused what is SWR is and how it’s caching works
yeah swr is purely client side.

by the way, nextjs has a ton of built-in server-side caching mechanisms, you most likely don't need to bring your own node-cache.
@joulev yeah swr is purely client side. by the way, nextjs has a ton of built-in server-side caching mechanisms, you most likely don't need to bring your own node-cache.
Eared TrogonOP
it is a bit of confusing problem i have actually. i am currently using api route for calling other api(korean weather forecast), and appears when we request and get response, it do not cache oncoming request even if response are identically same. so i need caching method to cache identical response for some time (for every 5 minute revalidate)
Eared TrogonOP
export async function GET(request) {
  const url = new URL(request.url);
  const searchParams = new URLSearchParams(url.searchParams);
  const administrativeArea = searchParams.get("administrativeArea");
  //get the administrativeArea from the query parameter

  if (!administrativeArea) {
    throw new Error("Administrative area is missing.");
  }
  //merge the administrativeArea with the capitalLocationData, and return the matched location data
  function mergeLocationsData(capitalLocationData, administrativeArea) {
    const matchedPlace = capitalLocationData.filter(
      (capital) => capital.administrativeArea === administrativeArea
    );
    const matchedLocation = matchedPlace.length > 0 ? matchedPlace[0] : {};
    return {
      ...matchedLocation,
    };
  }

  const locationData = mergeLocationsData(CAPITAL_LOCATION, administrativeArea);

  //cacheKey is the key to store the data in the cache
  const cacheKey = `weather_DB_${administrativeArea}`;

  //check if the data is already in the cache
  const cachedData = cache.get(cacheKey);
  if (cachedData) {
    console.log("Cached data:", cachedData);
    return NextResponse.json(cachedData);
  } else {
    console.log("No cached data for key:", cacheKey);
  }

  try {
    const currentWeatherData = await fetchWeatherDataWithRetry(
      "DB",
      "currentData",
      locationData,
      2000
    );
    const pastWeatherData = await fetchWeatherDataWithRetry(
      "DB",
      "pastData",
      locationData,
      2000
    );

    const RN1 = filterAndMapItems(currentWeatherData, "RN1");
    const PTY = filterAndMapItems(currentWeatherData, "PTY");
    const POP = filterAndMapItems(pastWeatherData, "POP");
    const didItRain = PTY.PTY.obsrValue > 0;

    const responseData = { didItRain, RN1, PTY, POP };

    // 응답 데이터를 캐시에 저장
    cache.set(cacheKey, responseData);

    return NextResponse.json(responseData);
  } catch (error) {
    console.error("Error fetching weather data:", error);
    throw new Error("Failed to fetch weather data");
  }
}

here is full code if you interested in
@Eared Trogon export async function GET(request) { const url = new URL(request.url); const searchParams = new URLSearchParams(url.searchParams); const administrativeArea = searchParams.get("administrativeArea"); //get the administrativeArea from the query parameter if (!administrativeArea) { throw new Error("Administrative area is missing."); } //merge the administrativeArea with the capitalLocationData, and return the matched location data function mergeLocationsData(capitalLocationData, administrativeArea) { const matchedPlace = capitalLocationData.filter( (capital) => capital.administrativeArea === administrativeArea ); const matchedLocation = matchedPlace.length > 0 ? matchedPlace[0] : {}; return { ...matchedLocation, }; } const locationData = mergeLocationsData(CAPITAL_LOCATION, administrativeArea); //cacheKey is the key to store the data in the cache const cacheKey = `weather_DB_${administrativeArea}`; //check if the data is already in the cache const cachedData = cache.get(cacheKey); if (cachedData) { console.log("Cached data:", cachedData); return NextResponse.json(cachedData); } else { console.log("No cached data for key:", cacheKey); } try { const currentWeatherData = await fetchWeatherDataWithRetry( "DB", "currentData", locationData, 2000 ); const pastWeatherData = await fetchWeatherDataWithRetry( "DB", "pastData", locationData, 2000 ); const RN1 = filterAndMapItems(currentWeatherData, "RN1"); const PTY = filterAndMapItems(currentWeatherData, "PTY"); const POP = filterAndMapItems(pastWeatherData, "POP"); const didItRain = PTY.PTY.obsrValue > 0; const responseData = { didItRain, RN1, PTY, POP }; // 응답 데이터를 캐시에 저장 cache.set(cacheKey, responseData); return NextResponse.json(responseData); } catch (error) { console.error("Error fetching weather data:", error); throw new Error("Failed to fetch weather data"); } } here is full code if you interested in
if you use fetch behind the scenes, [you can use next.revalidate](https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnextrevalidate):
fetch("...", {
  next: { revalidate: 300 }
})


if you don't use fetch, the simplest method would be to use unstable_cache,
unstable_cache(
  async () => {...},
  [],
  { revalidate: 300 }
)

then the async () => { } callback is only called once every 300 seconds.
Eared TrogonOP
Thanks, i will try them out but fetchWeatherDataWithRetry uses axios for fetching stuff for now
i would recommend switching to fetch. https://www.adios-axios.com