next-plugin-query-cache ·

A build-time query cache for Next.js. Works by creating an HTTP server during the build that caches responses.
Motivation
Unlike Gatsby, Next.js does not provide any sort of shared data layer. This is nice because it's simple and unopinionated. However, in large static sites with many repeated queries, there's a missed opportunity to cache results and share them between pages.
next-plugin-query-cache aims to do just that. During the build, it creates an HTTP proxy server that all concurrent build processes can go through to request a resource.
- If the proxy already has the value, it'll return it instead of fetching it.
- If a requested resource already has a request inflight, the proxy will wait till that request is finished before returning it.
- There's also an optional in-memory cache made for per-page queries (e.g. after the build for SSR or ISR).
Installation
Install
yarn add next-plugin-query-cache
or
npm i next-plugin-query-cache
Add to next.config.js
const createNextPluginQueryCache = require('next-plugin-query-cache/config');
const withNextPluginQueryCache = createNextPluginQueryCache({
port: 4000,
disableProxy: process.env.DISABLE_PROXY === 'true',
fetch: require('@vercel/fetch')(require('node-fetch')),
calculateCacheKey: (url, options) => url,
});
module.exports = withNextPluginQueryCache();
Create the client queryFetch function
next-plugin-query-cache returns a decorated window.fetch implementation. Whenever you call this wrapped fetch, it will check the cache. If the resource is not in the cache, it will make a real request.
To create this decorated fetch function, call createQueryFetch.
import { createQueryFetch } from 'next-plugin-query-cache';
const { queryFetch, cache } = createQueryFetch({
port: process.env.NEXT_QUERY_CACHE_PORT,
fetch: fetch,
shouldCache: (url, options) => {
const method = options?.method?.toUpperCase() || 'GET';
return method === 'GET' && typeof url === 'string';
},
getProxyEnabled: async () =>
(process.env.CI === 'true' ||
process.env.NEXT_PLUGIN_QUERY_CACHE_ACTIVE === 'true') &&
!!process.env.NEXT_QUERY_CACHE_PORT,
getInMemoryCacheEnabled: async () => true,
calculateCacheKey: (url) => url,
});
cache.clear();
export default queryFetch;
Usage
After you create the queryFetch function, use it like you would use the default fetch.
Note that you should only use this queryFetch inside of getStaticProps.
import queryFetch from '../query-fetch';
export const getStaticProps = async () => {
const response = await queryFetch('https://some-service.com', {
headers: {
accept: 'application/json',
},
});
const data = await response.json();
return { props: { data } };
};
function MyPage({ data }) {
return (
<div>
<h1>My Page</h1>
<pre>{JSON.string(data, null, 2)}</pre>
</div>
);
}
export default MyPage;