Next Cache Tools

Getting Started

Installation and setup guide for next-cache-tools

next-cache-tools provides an ergonomic API for managing Next.js cache tags. It works with Next.js's "use cache" directive and cacheTag function to simplify cache invalidation and lifecycle management.

Installation

Install the package using your preferred package manager:

npm i next-cache-tools

Quick Start

Basic Cache Tag

import { createCacheTag } from "next-cache-tools";

const userTag = createCacheTag("user", {
  getCacheId: ({ id }: { id: string }) => id,
});

async function getUser(id: string) {
  "use cache";
  
  userTag.tag({ id });
  
  return { id, name: `User ${id}` };
}

When getCacheId is not provided, the tag name is used as the cache ID and you can call .tag() without arguments:

const metricsTag = createCacheTag("metrics");

async function getMetrics() {
  "use cache";
  
  metricsTag.tag();
  
  return { cpu: 50, memory: 8000 };
}

Using Cache Tags

import { userTag } from "@/app/cache";

async function getUserById(id: string) {
  "use cache";
  
  userTag.tag({ id });
  userTag.life({ profile: "max" });
  
  return { id, name: `User ${id}` };
}

Learn more about Cache Tags.

Revalidating Cache Tags

To revalidate or update cache entries:

import { userTag } from "@/app/cache";

// Revalidate all entries for this tag
userTag.revalidate();

// Revalidate a specific user
userTag.revalidate({
  filter: { id: "user-123" },
});

// Update all entries for this tag
userTag.update();

// Update a specific user
userTag.update({
  filter: { id: "user-123" },
});

Learn more about Revalidation & Updates.

(Optional) Group your Tags

Cache groups allow you to organize related cache tags hierarchically and perform bulk operations on deeply nested structures. You can call .revalidate() and .update() at any level of the hierarchy to manage related caches efficiently.

import { createCacheTag, createCacheTagGroup } from "next-cache-tools";

export const cacheGroup = createCacheTagGroup("users", {
  user: {
    byId: createCacheTag("byId", {
      getCacheId: ({ id }: { id: string }) => id,
    }),
    byEmail: createCacheTag("byEmail", {
      getCacheId: ({ email }: { email: string }) => email,
    }),
  },
});
import { cacheGroup } from "@/app/cache";

async function getUserById(id: string) {
  "use cache";
  
  cacheGroup.user.byId.tag({ id });
  
  return { id, name: `User ${id}` };
}

Learn more about Cache Groups.