I have the basic setup of server-side rendering with react-query setup and it works as expected. I know that react-query maintains a cache on the client side from which it can server data if the particular query key is fresh and it exists. This setup looks like this -
// pages/_app.tsx
import type { AppProps } from "next/app";
import { QueryClient, QueryClientProvider, Hydrate } from "react-query";
function MyApp({ Component, pageProps }: AppProps) {
const [queryClient] = React.useState(() => new QueryClient());
return (
<QueryClientProvider client={queryClient}>
<Hydrate state={pageProps.dehydratedState}>
<Component {...pageProps} />
</Hydrate>
</QueryClientProvider>
);
}
export default MyApp;
// pages/index.tsx
import React from "react";
import { GetServerSideProps, NextPage } from "next";
import { dehydrate } from "react-query";
import { useQuery } from "react-query";
import { exampleApi } from "@src/modules/my-plans/apis";
const ListingPage: NextPage = () => {
const { data: list, isLoading } = useQuery(["list-api-key"], exampleApi);
return (
<main>
{...}
</main>
);
};
export const getServerSideProps: GetServerSideProps = async (context) => {
const queryClient = new QueryClient();
await queryClient.prefetchQuery(["list-api-key"], exampleApi);
return {
props: {
dehydratedState: dehydrate(queryClientTopDog)
}
};
};
export default ListingPage;
In the above snippet, since the API is prefetched in getServerSideProps
, useQuery
fetches the data from the hydrated cache instead of calling the API.
What I am trying to figure out is if caching in getServerSideProps
is possible. Since the API has been called once, how can I make it so that from the second request on, instead of calling the API again it fetches data from a server-side cache similar to how react-query maintains a client-side cache?
If I am not misunderstanding this page in the docs, it seem to indicate that it is possible to maintain a server-side cache but I am unable to figure out how to do it. For this I have tried creating a QueryClient
on pages/_app.tsx
and exported it to use in getServerSideProps
but I am not able to get it to work.