Store data in redis (server-side) or sessionStorage (client-side) with expiry time (seconds) using NextJS.
Add redis and redis-mock (for testing):
yarn add redis redis-mock
Copy cacheable.js
and redis.js
to lib/
.
Make your calls with cacheable(key, expiration, callback)
.
key
is a unique cache key for matchingexpiration
is seconds to persist cache value, e.g. 30 seconds will expire after 30 secondscallback
is your callback function to execute if cached result does not exist. The result will then be stored into cache.
import cacheable from 'lib/cacheable.js';
export const fetchPage = async id => {
const key = `pages:${id}`; // cache key
const expiry = 60; // in seconds
return cacheable(key, expiry, async () => {
const resp = await axios.get(`https://data.ltd/pages/${id}.json`);
return resp.body;
});
};