neshClassicCache
neshClassicCache
allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests. Unlike the neshCache
or unstable_cache
↗ function, neshClassicCache
must be used in a Next.js Pages Router allowing users to cache data in the getServerSideProps
and API routes.
This function is experimental, the API may change in the future. Use with caution.
Cache entries created with neshClassicCache
can be revalidated only by the revalidateTag
↗ method.
Parameters
fetchData
This is an asynchronous function that fetches the data you want to cache. It must be a function that returns a Promise
.
commonOptions
This is an object that controls how the cache behaves. It can contain the following properties:
-
tags
- An array of tags to associate with the cached result. Tags are used to revalidate the cache using therevalidateTag
andrevalidatePath
functions. -
revalidate
- The revalidation interval in seconds. Must be a positive integer orfalse
to disable revalidation. Defaults toexport const revalidate = time;
in the current route. -
argumentsSerializer
- A function that serializes the arguments passed to the callback function. Use it to create a cache key. Defaults toJSON.stringify(args)
. -
resultSerializer
- A function that serializes the result of the callback function.Defaults toBuffer.from(JSON.stringify(data)).toString('base64')
. -
resultDeserializer
- A function that deserializes the string representation of the result of the callback function. Defaults toJSON.parse(Buffer.from(data, 'base64').toString('utf-8'))
. -
responseContext
- The response context object. If provided, it is used to set the cache headers acoording to therevalidate
option. Defaults toundefined
.
Returns
neshClassicCache
returns a function that when invoked, returns a Promise
that resolves to the cached data. If the data is not in the cache, the provided function will be invoked, and its result will be cached and returned. The first argument is the options
which can be used to override the common options
. In addition, there is a cacheKey
option that can be used to provide a custom cache key.
Example
import { neshClassicCache } from '@neshca/cache-handler/functions';
import axios from 'axios';
export const config = {
runtime: 'nodejs',
};
async function getViaAxios(url) {
try {
return (await axios.get(url.href)).data;
} catch (_error) {
return null;
}
}
const cachedAxios = neshClassicCache(getViaAxios);
export default async function handler(request, response) {
if (request.method !== 'GET') {
return response.status(405).send(null);
}
const revalidate = 5;
const url = new URL('https://api.example.com/data.json');
// Add tags to be able to revalidate the cache
const data = await cachedAxios({ revalidate, tags: [url.pathname], responseContext: response }, url);
if (!data) {
response.status(404).send('Not found');
return;
}
response.json(data);
}