Search

Server Query

How to fetch on server with cached data

To fetch cached data in Server Components, use the serverQuery function.

Query Pattern

When fetching cached data in Server Components, the following sequence occurs:

Cached DataFetched from the serverAPISingaporeServerSan FranciscoBrowserSan Francisco
StepEnvironmentDescription
PreBrowserSends a request to the server for the website at https://example.com.
1ServerIf external data is required, locates the cached response for the relevant API query.
2ServerSends the rendered HTML containing the cached data to the browser.
3BrowserReceives the response, hydrates the page, and displays the data.
PostServerAfter responding, checks whether the cached data is stale. If so, it fetches fresh data from the API to update the cache for subsequent requests.

GET Request

The following example fetches data on the server using a GET request. To cache the response on the server, set queryCache to true or pass an object with custom cache options.

import { serverQuery } from "@bigbang-sdk/next-query";

async function ServerComponent() {
  const { data, error } = await serverQuery({
        queryUrl: "https://api.example.com/data",
        queryCache: true
      });

  console.log(data, error);
}

Cache Options

You can also pass an object to the queryCache parameter to customize caching behavior.

Cache Tags

Use the tags property to assign one or more tags to the cached response. These tags can later be revalidated by calling the revalidateTag function from Next.js's internal next/cache module with the same tag.

import { serverQuery } from "@bigbang-sdk/next-query";

async function ServerComponent() {
  const { data, error } = await serverQuery({
        queryUrl: "https://api.example.com/data",
        queryCache: {
          tags: ["user", "profile"],
        },
      });

  console.log(data, error);
}

Cache Revalidation

You can pass a number to the revalidate property to specify how many seconds the data is considered fresh.

After this period, the data is considered stale. When the query is fetched again, the cached data is returned while fresh data is fetched in the background. The updated data will be served on the following request.

import { serverQuery } from "@bigbang-sdk/next-query";

async function ServerComponent() {
  const { data, error } = await serverQuery({
        queryUrl: "https://api.example.com/data",
        queryCache: {
          revalidate: 60,
        },
      });

  console.log(data, error);
}

Made with

by Bigbang