Getting Started with @neshca/cache-handler
This section guides you through the initial setup and basic usage of @neshca/cache-handler
, helping you integrate advanced caching solutions into your Next.js applications seamlessly.
Prerequisites
- Node.js: 18.17 or newer.
- Next.js: 13.5.1 or newer (below 15.0.0).
- Redis (optional): 4.6.0 or newer.
Quick Start Installation
npx create-next-app --example cache-handler-redis cache-handler-redis-app
yarn create next-app --example cache-handler-redis cache-handler-redis-app
pnpm create next-app --example cache-handler-redis cache-handler-redis-app
Manual installation
-
Install
@neshca/cache-handler
:
Execute this command in your Next.js project root directory:npm install @neshca/cache-handler
-
Optional Redis Installation:
Install Redis if you plan to use it as your cache store:npm install redis
Basic Custom Configuration
-
Create a Cache Handler File:
In your project root, create a file namedcache-handler.mjs
for your cache configuration. -
Configure the Cache Handler:
Below is a basic setup example:cache-handler.mjsimport { CacheHandler } from '@neshca/cache-handler'; CacheHandler.onCreation(async () => { // Let's imagine we're using a map // in which values are shared via the network // between all your Next.js app instances. const cacheStore = new MagicMap(); const handler = { async get(key) { return await cacheStore.get(key); }, async set(key, value) { await cacheStore.set(key, value); }, async revalidateTag(tag) { // Iterate over all entries in the cache for (const [key, { tags }] of cacheStore) { // If the value's tags include the specified tag, delete this entry if (tags.includes(tag)) { await cacheStore.delete(key); } } }, // Optional: Implement the delete method // if your cache store doesn't support automatic time-based key expiration. // It will be called when the get method returns expired data. async delete(key) { await cacheStore.delete(key); }, }; return { handlers: [handler], }; }); export default CacheHandler;
Do not import
@neshca/cache-handler
to your client components or pages. It is only meant to be used incache-handler.mjs
files. -
Integrate with Next.js:
Update yournext.config.js
to utilize the cache handler, ensuring it’s only active in production:next.config.jsconst nextConfig = { cacheHandler: process.env.NODE_ENV === 'production' ? require.resolve('./cache-handler.mjs') : undefined, // Use `experimental` option instead of the `cacheHandler` property when using Next.js versions from 13.5.1 to 14.0.4 /* experimental: { incrementalCacheHandlerPath: process.env.NODE_ENV === 'production' ? require.resolve('./cache-handler.mjs') : undefined, }, */ experimental: { // This is required for the experimental feature of pre-populating the cache with the initial data instrumentationHook: true, }, }; module.exports = nextConfig;
-
Populate the Cache with Prerendered Pages: Next.js pre-renders pages during the build process and stores them on the disk. This procedure bypasses the
CacheHandler
, so pre-rendered pages and routes are not added to the CacheHandler cache stores. To populate the cache with the initial data, you can utilize theregisterInitialCache
function from@neshca/cache-handler/instrumentation
:instrumentation.tsexport async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { const { registerInitialCache } = await import('@neshca/cache-handler/instrumentation'); // Assuming that your CacheHandler configuration is in the root of the project and the instrumentation is in the src directory. // Please adjust the path accordingly. // CommonJS CacheHandler configuration is also supported. const CacheHandler = (await import('../cache-handler.mjs')).default; await registerInitialCache(CacheHandler); } }
Use
NEXT_RUNTIME
environment variable to ensure that the instrumentation is only executed in Node.js. Use dynamic import to avoid bundling issues.This instrumentation will fill the cache with the initial data when the application starts. The duration of this process may vary based on the number and size of pages, routes, and fetch calls. For more information refer to the Populating the Cache with the initial data section.
Running Your Application
Start Your Next.js Application:
Build and start your application in production mode to see the cache handler in action:
npm run build
npm run start
Next Steps
With the setup complete, explore @neshca/cache-handler
’s advanced features:
- Check out the Redis Integration Example.
- Learn how to use the API.
- See how to debug and troubleshoot your cache handler configuration.