Skip to article content
LESSON 13 / 28

Cache Components and cache identity

Choose what may be reused, define a collision-resistant application cache key, and keep current and previous Next.js cache models distinct.

What you will be able to do

  • Explain cache identity, lifetime and invalidation independently.
  • Use Cache Components only with an explicit supported configuration.
  • Prevent cross-query and cross-tenant reuse by including the relevant inputs.

Caching is a claim that a prior result remains usable

A cached result is associated with inputs and a reuse policy. Before naming an API, answer three questions: which calls mean the same thing, how long may an answer be reused, and which events make it unsuitable? For a public catalogue, query and sort order change the result. Locale can change labels. Tenant identity can change which records exist. Omitting one relevant input turns a speed optimization into a correctness defect.

Not all state described as a cache has the same scope. Request memoization avoids repeated work within a render. Server data or rendered output caches can survive later requests. The browser’s router and a client query library can retain their own representations. HTTP intermediaries may cache responses too. A stale screen must be traced to the owner of the stale value rather than treated as one mysterious universal cache.

Keep the two framework models explicit

Current Next.js supports Cache Components, including use cache and related lifetime and tagging APIs. This course uses explicit configuration in examples so readers can identify the model under discussion. The previous App Router caching model has different mechanisms and route-level options. Do not combine snippets from both models without checking compatibility and intended semantics against the pinned version.

The example marks a public snapshot as reusable and gives it a tag and lifetime. It contains only public teaching data. A request-dependent value such as cookies or headers should be read in an appropriate request scope rather than casually accessed inside a shared cached function. Passing a value as an argument makes it part of the function’s input reasoning, but that alone does not authorize exposing it or make personalized caching appropriate.

Project configuration

next.config.ts
import type { NextConfig } from 'next';
const config: NextConfig = { cacheComponents: true };
export default config;

Server execution

app/lib/catalog-snapshot.ts
import { cacheLife, cacheTag } from 'next/cache';
export async function getPublicCatalogSnapshot(sort: 'name' | 'price') {
  'use cache';
  cacheTag('public-catalog');
  cacheLife('minutes');
  const products = [
    { id: 'keyboard', title: 'Keyboard', priceCents: 6500 },
    { id: 'monitor', title: 'Monitor', priceCents: 22000 }
  ];
  products.sort(sort === 'price'
    ? (a, b) => a.priceCents - b.priceCents
    : (a, b) => a.title.localeCompare(b.title));
  return { generatedAt: new Date().toISOString(), products };
}

PAUSE AND PREDICT

A shared cache key contains only query and sort, but results also depend on tenant and locale. Which defect is most serious?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Canonicalize equivalent inputs without collapsing different ones

If filter tags are semantically a set, red and large describe the same request as large and red. Sort and deduplicate them before forming an application-level cache key. Normalize only differences the domain declares irrelevant. Lowercasing a case-sensitive identifier or stripping a meaningful locale distinction can incorrectly collapse different requests. The kata explicitly declares that query case and surrounding whitespace do not change its search semantics.

Use a structured encoding rather than joining fields with a delimiter that may occur in the values. JSON encoding of an ordered tuple is sufficient for the small canonical key in this exercise. It is not a recreation of Next.js internal key generation. Framework caching handles its own identities; this exercise teaches the same input-analysis skill for custom service caches, client query keys and debugging.

Choose lifetime from the product, not a convenient number

A marketing description may tolerate delayed freshness while a permission decision or checkout stock check may not. State the acceptable staleness for each value and choose a strategy accordingly. A cache hit saves computation but can add complexity to invalidation and observability. Include cache identity and age in safe diagnostic metadata when needed, while keeping private keys and user data out of public logs.

Validate cache behavior under a production build and repeat requests with changed inputs. In a multi-instance deployment, per-process memory is not automatically shared. A cached item on one node may outlive invalidation on another unless the deployment coordinates them. The self-hosting module covers that operational boundary. For this lesson, prove correct identity and intentional lifetime before optimizing hit rate.

PAUSE AND PREDICT

Filter tags are a set, so [red,large] and [large,red,red] mean the same search. What canonicalization is appropriate under that stated contract?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Misconceptions to replace

Compare the tempting shortcut with the model you can verify in code.

CLAIM TO CHALLENGEOne cache invalidation API automatically refreshes browser query caches, router caches and every server instance.
A more accurate model

These representations have different owners and scopes. Trace the visible stale value and update each relevant layer deliberately.

How to check it

N10, N11 and N25 describe server and deployment cache concerns; client-server-sync covers browser query representations.

CLAIM TO CHALLENGEA cache key that includes user input is safe because the key is unique.
A more accurate model

Uniqueness does not validate identity, authorize data access or choose an acceptable lifetime. Cache correctness requires all of those decisions.

How to check it

N19 and N20 cover trust and authorization; the cache identity kata isolates encoding only.

Mistakes to catch in your own code

  • Do not use a shared cache key that omits tenant, locale or other result-changing inputs.
  • Do not call request memoization a durable cross-request cache.
  • Do not mix previous-model route settings and Cache Components examples without a version/configuration check.

Write it by hand

JavaScript logic playground

Create a canonical application cache key

Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.

  1. Implement solve({tenantId,locale,query,sort,filters}). All scalar fields are strings; filters is an array of strings and has set semantics.
  2. Trim and lowercase query. Deduplicate and lexicographically sort filters without changing the case of filter values. Preserve tenantId, locale and sort exactly.
  3. Return JSON.stringify([tenantId,locale,normalizedQuery,sort,normalizedFilters]). This is an application-key exercise, not the internal Next.js cache algorithm.

Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 4 test cases
  1. Normalize equivalent search and filters

    Input

    {
      "tenantId": "t1",
      "locale": "en-IN",
      "query": "  React  ",
      "sort": "name",
      "filters": [
        "large",
        "red",
        "large"
      ]
    }

    Expected

    "[\"t1\",\"en-IN\",\"react\",\"name\",[\"large\",\"red\"]]"
  2. Tenant remains part of identity

    Input

    {
      "tenantId": "t2",
      "locale": "en-IN",
      "query": "react",
      "sort": "name",
      "filters": [
        "red",
        "large"
      ]
    }

    Expected

    "[\"t2\",\"en-IN\",\"react\",\"name\",[\"large\",\"red\"]]"
  3. Delimiter characters stay unambiguous

    Input

    {
      "tenantId": "a|b",
      "locale": "c",
      "query": "",
      "sort": "name",
      "filters": []
    }

    Expected

    "[\"a|b\",\"c\",\"\",\"name\",[]]"
  4. Do not change case-sensitive filters

    Input

    {
      "tenantId": "t1",
      "locale": "tr",
      "query": " x ",
      "sort": "price",
      "filters": [
        "A",
        "a"
      ]
    }

    Expected

    "[\"t1\",\"tr\",\"x\",\"price\",[\"A\",\"a\"]]"
Reveal the worked solution and reasoning
solution.js
function solve(input) {
  const normalizedQuery = input.query.trim().toLowerCase();
  const filters = Array.from(new Set(input.filters)).sort();
  return JSON.stringify([input.tenantId, input.locale, normalizedQuery, input.sort, filters]);
}

Structured encoding preserves field boundaries even when values contain delimiter characters.

Normalization follows the declared domain contract. A production cache must additionally enforce authorized identity, lifetime and invalidation.

Verify it in a real Next.js application

Next.js application lab

Observe the shipped public catalogue cache

Open the local application route /cache after starting the workbench. Follow the experiment and collect the evidence described below.

Make the change

  1. Read next.config.ts and lib/catalog.ts. Cache Components is already enabled; getCatalog uses use cache, cacheLife("minutes") and cacheTag("catalog") around a public product projection.
  2. Build and start the production app, sign in as Ada and visit /cache. Record the displayed product price and version, then compare /catalog/keyboard and /api/catalog?q=keyboard.
  3. For an explicit observation experiment, add a temporary server log inside getCatalog, rebuild and repeat reads before and after the shipped price action. Distinguish a cached function execution from an HTTP request to the no-store JSON endpoint.
  4. As an extension, introduce a public result-changing argument to a cached helper, call it with distinct and equivalent normalized inputs, and test the intended identity. Do not add cookie reads or private account data inside this public cache.

Check the behavior

  • The report names the actual enabled caching model and tag.
  • Price and version agree across the intended public views after the supported action invalidates the tag.
  • Repeated identical values are not treated as proof of a cache hit without observing the helper execution.
  • If the argument extension is implemented, different result-changing inputs cannot accidentally share an application-level key.
Review the application reasoning

The shipped lab displays a product version, not a generatedAt timestamp. Version shows data changes; temporary instrumentation helps observe reuse without inventing a marker that is absent from the project.

The JSON endpoint's no-store response policy and the inner cached data function concern different layers. The canonical-key kata is an application model, not a reproduction of Next.js cache internals.

Open the project files and run instructions

A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.

The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.

Terminal
cd nextjs-interview-lab
npm ci
npm run dev

# In a second terminal
npm test

# Stop dev, then verify the production application
npm run build
npm start

# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2e

Open http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.

Explain it in an interview

Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.

  1. 01What must you define before adding a cache?

    I define identity, acceptable lifetime and invalidation events. I also name the cache scope and the source of truth. Without those decisions, a cache may be fast but return data for the wrong query or remain stale after a mutation. I test changes to each result-affecting input.

    Follow-up questions

    • Which inputs belong in a tenant-specific key?
    • What is the staleness budget for stock?
  2. 02How would you explain use cache in this course?

    It marks a reusable result in the Cache Components model, which this course enables explicitly in its example configuration. I pair it with deliberate input, lifetime and tag decisions. I do not assume an older fetch or route-config tutorial has identical behavior under that model.

    Follow-up questions

    • How do request cookies fit into the design?
    • What belongs outside a shared cached scope?
  3. 03Why normalize a cache key?

    Equivalent requests should share a key, while different results must stay distinct. I normalize only domain-declared equivalences such as the order of set-valued filters. I use structured encoding so a separator inside user input cannot make different input tuples collide.

    Follow-up questions

    • When would lowercasing be incorrect?
    • How does a client query key relate to a server cache key?
  4. 04Are browser query caches and server caches interchangeable?

    No. They have different owners, lifetimes and invalidation mechanisms. A server mutation can update the source of truth while a client query cache still shows an earlier representation. I trace which layer produced the visible value and refresh or invalidate the relevant layer deliberately.

    Follow-up questions

    • What does router.refresh leave unchanged?
    • What changes with several server instances?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

An old tutorial uses previous-model route settings. Your example enables Cache Components. What should you do before combining its snippets?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.