🎉 Version 1.8.0 is out! Use shared cache for the Next.js Pages API routes and getServerSideProps with neshClassicCache
Usage guidesBuild Id as a Prefix Key

Let me quote from the Next.js documentation ↗.

Next.js generates an ID during next build to identify which version of your application is being served. The same build should be used and boot up multiple containers.

If you are rebuilding for each stage of your environment, you will need to generate a consistent buildId to use between containers. Use the generateBuildId command in next.config.js:

next.config.js
const nextConfig = {
  generateBuildId: async () => {
    // This could be anything, using the latest git hash
    return process.env.GIT_HASH;
  },
};

To use buildId for prefixing the cache keys, use either of the following solutions.:

Using process.env.GIT_HASH

cache-handler.mjs
CacheHandler.onCreation(async () => {
  await client.connect();
 
  const handler = await createRedisHandler({
    client,
    keyPrefix: process.env.GIT_HASH,
  });
 
  return {
    handlers: [handler],
  };
});

Using without generateBuildId

In this case, you must build your app once and use the same build to deploy to all environments.

next.config.js
const nextConfig = {
  output: 'standalone',
};
cache-handler.mjs
CacheHandler.onCreation(async ({ buildId }) => {
  let handler;
 
  if (buildId) {
    await client.connect();
 
    handler = await createRedisHandler({
      client,
      keyPrefix: `${buildId}:`,
    });
  }
 
  return {
    handlers: [handler],
  };
});

Limitations:

  • Some cache values may be lost during the build process because the buildId is defined after some cache values have already been set. However, buildId will be defined from the beginning when you start your app.