Documentation
Getting Started
Functions
Guides
Concepts
Server Query
How to fetch on server with cached dataTo fetch cached data in Server Components, use the serverQuery
function.
When fetching cached data in Server Components, the following sequence occurs:
Step | Environment | Description |
---|---|---|
Pre | Browser | Sends a request to the server for the website at https://example.com . |
1 | Server | If external data is required, locates the cached response for the relevant API query. |
2 | Server | Sends the rendered HTML containing the cached data to the browser. |
3 | Browser | Receives the response, hydrates the page, and displays the data. |
Post | Server | After responding, checks whether the cached data is stale. If so, it fetches fresh data from the API to update the cache for subsequent requests. |
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);
}
You can also pass an object to the queryCache
parameter to customize caching behavior.
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);
}
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