Skip to content

Caching

The following guide will show you caching and revalidation techniques of pages and handlers in Zuby.js. The caching can be done in two ways:

Internal caching

The internal caching is done by Zuby.js itself. It will cache any server-side rendered page or handler in the memory and serve the cached version to the user if the path is requested again

The internal caching is disabled by default and can be enabled by setting the cache option to desired TTL (time to live) in seconds. In the following example, we will enable the internal caching for 60 seconds for both pages and handlers on given path.

pages/products/[id].js
import fetchProduct from '../../api/fetchProduct.js';
export default async function Handler({ context }) {
const { id } = context.params;
const product = await fetchProduct(id);
context.props = {
product
};
context.cache = 60;
}
pages/products/[id].jsx
export const prerender = false;
export default function Products({ product, context }) {
const { title, description, price } = product;
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
<p>{price}</p>
</div>
);
}

With this technique you can implement ISR (Incremental Static Regeneration) in your application and generate static-like pages on the fly just when they are requested by setting the cache option to ridiculously high number.

pages/products/[id].js
import fetchProduct from '../../api/fetchProduct.js';
export default async function Handler({ context }) {
const { id } = context.params;
const product = await fetchProduct(id);
context.props = {
product
};
// Cache page for 1 year
context.cache = 365 * 24 * 60 * 60;
}

External caching

The external caching can be done by using the Cache-Control header together with external caching service like Cloudflare or Vercel Edge Network.

The Cache-Control header can be set in the context object in the handler. The following example will instruct the CDN to cache the page for 1 hour and the client’s web browser to cache the page for 5 minutes.

pages/products/[id].js
import fetchProduct from '../../api/fetchProduct.js';
export default async function Handler({ context }) {
const { id } = context.params;
const product = await fetchProduct(id);
context.props = {
product
};
// Cache page for 1 hour by CDN and 5 minutes by web browser
context.headers.set('Cache-Control', 's-maxage=3600, max-age=300');
}