DEV Community

Cover image for Frontend Caching in Cabloy/Zova vs Next.js
Uncle Pushui
Uncle Pushui

Posted on

Frontend Caching in Cabloy/Zova vs Next.js

Zova caches state; Next.js caches rendered output. They are not two ways of doing the same thing — they are answers to two different problems.

The most common mistake when comparing caches is assuming they solve the same problem.

Both Zova and Next.js have caches, but they start from opposite ends:

  • Zova's cache is for Vue SPA + SSR — the core question is "if the user closes the browser and comes back, do the orders I was looking at still show up?" and "after user A logs out and user B logs in, does the old data get wiped clean?" It is a client-side state persistence layer.
  • Next.js's cache is for React full-stack SSR/SSG — the core question is "can this route be pre-rendered and returned directly without re-running React on every request?" and "can fetch results be reused across requests?" It is a rendering performance optimization layer.

So comparing them by API names alone misses the point. You have to see what problem each one is actually trying to answer.

Let's start with Zova, see exactly what it caches and why, then bring Next.js over for a side-by-side.


1. Zova's Five-Layer Cache Architecture

Zova's cache lives inside the a-model module — the Model layer. The entry point is moduleLoaded() in storage.ts:

async moduleLoaded() {
  const options = deepExtend({}, this.scope.config.queryClientConfig.defaultOptions);
  if (process.env.SERVER) {
    options.queries ??= {};
    options.queries.gcTime = Infinity;   // no auto GC during SSR
  }
  const queryCache = new QueryCache();
  const queryClient = new QueryClient({ defaultOptions: options, queryCache });
  this._persistence = new ModelPersistenceContext(queryClient, this.sys.env.SITE_ID);
  this.app.vue.use(VueQueryPlugin, { queryClient });
}
Enter fullscreen mode Exit fullscreen mode

The baseline defaults come from config.ts:

const defaultOptions = {
  queries: {
    retry: false,
    refetchOnWindowFocus: false,
    refetchOnMount: false,
    refetchOnReconnect: true,
    gcTime: 1000 * 60 * 5,   // 5 minutes default
  },
  dehydrate: {
    shouldDehydrateQuery(query) {
      if (query.meta?.ssr?.dehydrate === false) return false;
      if (typeof query.meta?.persister === 'object' && query.meta?.persister?.sync) return false;
      return defaultShouldDehydrateQuery(query);
    },
    shouldDehydrateMutation(_mutation) { return false; },
  },
};
Enter fullscreen mode Exit fullscreen mode

The full architecture is five layers:

Layer 1: Memory — TanStack Vue Query QueryCache
  In-process query results for the app lifetime
  Default gcTime: 5min, refetchOnWindowFocus: false
  During SSR: gcTime = Infinity

Layer 2: Persistence — Query Persister
  cookie: session-level (session cookie)
  localStorage: permanent (Infinity)
  localforage/IndexedDB: default 24h maxAge
  Plus PersistenceQueue: serialized async writes + generation-based race prevention

Layer 3: Identity Isolation — ModelPersistenceContext
  scope = [instanceId, siteId, userId]
  scope changes → epoch++ → auto-invalidate all DB-persisted queries
  epoch token: stale operations silently dropped via CancelledError

Layer 4: SSR Response Cache — HTTP Cache-Control
  profile 'public': Cache-Control: public, max-age=N
  profile 'session': Cache-Control: private, no-store

Layer 5: Component Cache — Router Tabs + Vue KeepAlive
  tabsOptions.cache: true → tab state persisted to localStorage
  Vue KeepAlive: component instances cached in memory
Enter fullscreen mode Exit fullscreen mode

Layers 2, 3, and 5 are where Zova deviates from Next.js — those three either do not exist in Next.js or work on completely different principles.


2. Persistence Layer: Not an Optional Plugin

Zova re-implemented persistence rather than directly using @tanstack/query-persist-client, adding a generation mechanism on top. The core lives in bean.model.persister.ts.

Declaring persistence is a one-liner in a Model bean:

@Model()
export class ModelUserInfo extends BeanModelBase {
  $userInfo = this.$useQuery({
    queryKey: ['userInfo'],
    queryFn: () => api.getUserInfo(),
    meta: { persister: { storage: 'db' } }   // IndexedDB persistence
  });
}
Enter fullscreen mode Exit fullscreen mode

The three storage tiers and their default maxAge values are configured in config.ts:

persister: {
  maxAge: {
    cookie: undefined,    // undefined = session cookie
    local: Infinity,      // localStorage = forever
    db: 1000 * 60 * 60 * 24,   // IndexedDB = 24h
  },
  refetchOnRestore: true,
},
Enter fullscreen mode Exit fullscreen mode

The actual storage selection happens in _getPersisterStorage():

protected _getPersisterStorage(options, query) {
  if (options.storage === 'cookie') return CookieWrapper;
  if (process.env.SERVER) return undefined;   // SSR never writes to browser storage
  if (options.storage === 'local') return localStorage;
  if (options.storage === 'db') return localforage;
}
Enter fullscreen mode Exit fullscreen mode

That SSR branch is worth noting: during server-side rendering, persistence stays out of browser storage. SSR data instead goes through the dehydrate / hydrate pipeline — the QueryCache is serialized into the HTML, and the client restores it during hydration.

PersistenceQueue: Preventing Async Write Races

The most delicate piece of the persistence layer is persistenceQueue.ts.

IndexedDB operations are async and queue. Without protection, a "write A → delete A → write B" sequence could finish out of order and corrupt state. Zova uses a generation counter:

export class PersistenceQueue {
  private _generation = 0;
  private _keyGenerations = new Map<string, number>();

  generation(key: string): string {
    return `${this._generation}:${this._keyGenerations.get(key) ?? 0}`;
  }

  invalidate(key: string) {
    this._keyGenerations.set(key, (this._keyGenerations.get(key) ?? 0) + 1);
  }

  invalidateAll() {
    this._generation++;
    this._keyGenerations.clear();
  }
  // ...
}
Enter fullscreen mode Exit fullscreen mode

How it works:

  1. Before any save/remove on a key, queue.invalidate(key) increments that key's generation.
  2. When the async operation actually executes, it checks whether the generation matches what was captured at queue time.
  3. If a newer write has since invalidated the key, the old operation's generation is stale — it skips itself.
// bean.model.persister.ts _persisterSave()
const storageKey = this._getPersisterStorageKey(options, query);
const queue = getPersistenceQueue(storage);
queue.invalidate(storageKey);   // invalidate old generation first
// then enqueue the write...
Enter fullscreen mode Exit fullscreen mode

This guarantees "the newest write wins" and fixes the IndexedDB async ordering problem. Next.js's Router Cache and Data Cache are both in-process memory, so they never face this class of race.


3. Identity Isolation: scope + epoch token

This is Zova's unique design — Next.js simply has no concept of multi-tenancy.

modelPersistence.ts defines the core structures:

export type ModelPersistenceScope = readonly [string | null, string | null, string | null];
//                                 [instanceId, siteId, userId]

export interface ModelPersistenceToken {
  readonly scope: ModelPersistenceScope;
  readonly epoch: number;
}
Enter fullscreen mode Exit fullscreen mode

The scope is a triple [instanceId, siteId, userId]. Whenever the user's identity changes — logout, login to another account, switch workspace — the scope changes with it.

The full auto-invalidation flow lives in update():

update(values, options = {}) {
  const scope = Object.freeze([
    normalize(values.instanceId),
    normalize(values.siteId),
    normalize(values.userId),
  ]);
  if (scope.every((v, i) => v === this._scope[i])) {
    this._hydrated.clear();
    return;
  }
  // Find all queries that need invalidation — those with meta.persister.storage === 'db'
  const affected = this._queryClient
    .getQueryCache().getAll()
    .filter(query => isModelPersistenceDb(query.meta?.persister) && !(adopt && this._hydrated.has(query)));
  this._scope = scope;
  this._hydrated.clear();
  this._invalidate(affected);
  // Silently refetch active queries
  if (options.refetchActive === false) return;
  void Promise.resolve().then(() => {
    if (this.current(token)) {
      return this._queryClient.refetchQueries({
        type: 'active',
        predicate: query => affected.includes(query),
      });
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

What _invalidate() does:

private _invalidate(queries: Query[]) {
  this._epoch++;
  // Cancel all in-flight retries first (silent: true to prevent old error publication)
  for (const query of queries) void query.cancel({ silent: true, revert: false });
  notifyManager.batch(() => {
    for (const query of queries) {
      query.setOptions({ initialData: undefined, initialDataUpdatedAt: undefined });
      for (const observer of query.observers) {
        observer.setOptions({ initialData: undefined, placeholderData: undefined });
      }
      query.setState(emptyQueryState());
    }
  });
  this._version.value++;
  const token = this.capture();
  for (const listener of this._listeners) listener(token);
}
Enter fullscreen mode Exit fullscreen mode

The order matters: cancel first, then batch-reset all observer initialData/placeholderData, then clear query.state entirely.

epoch token: stale operations silently die

This is what guarantees "the instant scope changes, all in-flight work is automatically voided". Every persistence read/write/delete captures a token before executing and checks it when done:

// bean.model.persister.ts _createDbPersister()
const token = persistence.capture();
// ... async work happens ...
// on completion
if (options.storage !== 'db' || persistence.current(token)) {
  // scope unchanged — result is valid
} else {
  // scope changed — silently discard
}
Enter fullscreen mode Exit fullscreen mode

current(token) checks two things: epoch didn't change, and scope didn't change. Either one being different means false.

This is far more elegant than Next.js's manual revalidatePath / revalidateTag. In Next.js, you must manually trigger invalidation after every logout/login, and it only affects server-side caches. Zova ties all DB-persisted queries to the current scope and invalidates them automatically when scope transitions — plus cancels in-flight operations so stale data never writes back into the new identity's storage.

Storage keys are scope-aware too

Inside _getPersisterStorageKey():

return options.storage === 'db'
  ? getModelPersistenceStorageKey(
      this.sys.env.APP_NAME ?? '',
      (token ?? this.$modelPersistence.capture()).scope,
      logicalKey,
    )
  : logicalKey;
Enter fullscreen mode Exit fullscreen mode

The key format is ["zova-model-db", 1, appName, scope, logicalKey]. The scope is encoded into the key itself, so IndexedDB data for different identities is naturally isolated — even if you manually iterate keys they won't cross.


4. SSR Cache: Explicit Profile Declaration

Zova's SSR cache policy lives in ssrProfile.ts and ssrHandler.ts:

export function resolveSsrProfile(routeProfile, defaultProfile) {
  const ssrProfile = routeProfile ?? defaultProfile ?? 'public';
  if (ssrProfile !== 'public' && ssrProfile !== 'session') {
    throw new Error(`invalid SSR profile: ${ssrProfile}`);
  }
  return ssrProfile;
}
Enter fullscreen mode Exit fullscreen mode

Only two tiers: public and session. The HTTP header setup is straightforward:

if (ssrProfile === 'session') {
  options.res.setHeader('cache-control', 'private, no-store');
}
// ...
if (ssrProfile === 'public') {
  const expires = resolveSsrResponseCacheExpires(ssrProfileOptions.responseCache, this.sys.env.META_MODE);
  if (expires === 0) {
    res.setHeader('cache-control', 'no-cache, no-store, must-revalidate');
  } else {
    res.setHeader('cache-control', `public, max-age=${expires}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Development mode has special handling: metaMode === 'development' forces expires = 0, which gives no-cache, no-store, must-revalidate — preventing browser cache from getting in the way during development.

Zova's SSR cache is declarative and manual — each route picks ssrProfile: 'public' | 'session'. It never auto-detects. This is the opposite of Next.js App Router, which automatically excludes routes from the Full Route Cache when it detects dynamic APIs like cookies, headers, or searchParams.


5. Line Up Next.js

Now let's put Next.js App Router's four layers on the table. The docs are clear:

Next.js App Router Caching
Layer 1: Request Memoization (React)
  fetch GET/HEAD auto-deduplication within one React tree render
  Lifetime: single request
  Scope: React Component Tree only

Layer 2: Data Cache (Next.js built-in)
  fetch results persist across requests and deployments
  Default: no-store (not cached)
  Opt-in: cache: 'force-cache' or next.revalidate > 0
  Time-driven: stale-while-revalidate
  Event-driven: revalidateTag / revalidatePath

Layer 3: Full Route Cache (Next.js built-in)
  Pre-rendered HTML + RSC Payload
  Generated at build time or during ISR
  Invalidated by: Data Cache revalidate / redeploy
  Auto-exit: using cookies/headers/searchParams dynamic APIs

Layer 4: Router Cache (browser memory)
  Client-side RSC Payload cache
  Lifetime: session + auto-expiration
  Granularity: layout / loading / page segments
Enter fullscreen mode Exit fullscreen mode

Side-by-side

Dimension Zova (Vue frontend) Next.js (React full-stack)
Layers 5: memory + persistence + identity + SSR HTTP + KeepAlive 4: memoization + Data + Full Route + Router
Persistence storage Cookie / localStorage / IndexedDB None (browser BFCache + server disk/memory)
Default persistence non-DB queries in memory; DB queries in IndexedDB (24h) Memory only
Identity isolation ✅ scope=[iid,siteId,userId] epoch token ❌ not in scope
SSR data transfer QueryCache dehydrate → window.INITIAL_STATE_DEFER RSC Payload → React reconciliation
SSR cache policy Explicit profile public / session Auto-inferred from fetch options + Route Segment Config
Async safety PersistenceQueue generation + CancelledError silent SWR background refresh
Invalidation trigger scope change → auto-invalidate + epoch++ Manual revalidateTag / revalidatePath

TTL semantics are fundamentally different

Zova's TTL is maxAge — when it expires the data is gone. Next.js's revalidate: N is stale-while-revalidate — after expiry it still returns the stale data and silently refreshes in the background.

Zova Next.js
Time meaning Data lifespan Maximum time before the server initiates a refresh
After expiry Discarded; next fetch loads fresh Stale data still returned; refresh fires in background
User impact Loading state on first post-expiry fetch Instant response even after expiry
Best for User-sensitive data (Auth tokens, captchas) Low-sensitivity data (blog posts, product listings)

Default behavior points in opposite directions

Zova's defaults are refetchOnMount: false, refetchOnWindowFocus: false, gcTime: 5min — leaning toward minimizing requests and trusting cache.

Next.js's default fetch setting is cache: 'no-store' — leaning toward freshness by default, with cache as an explicit opt-in optimization.

The defaults answer opposite questions:

  • Zova defaults to "trust the cache" — SPA users expect data to persist across navigations and not flicker. Cache invalidation is a precise, controlled operation (scope change, manual invalidate).
  • Next.js defaults to "don't trust anything" — server-side rendering must guarantee freshness. Caching is an opt-in performance optimization, not the default.

6. Three Zova-Specific Cache Details

1. gcTime is Infinity during SSR

if (process.env.SERVER) {
  options.queries ??= {};
  options.queries.gcTime = Infinity;
}
Enter fullscreen mode Exit fullscreen mode

This means no auto GC during SSR. The reason is straightforward: all queries in the QueryCache during SSR end up dehydrated into the HTML. If one got GC'd before dehydration, the serialized cache would be incomplete.

Next.js never faces this — each server render is isolated, and the Data Cache is a separate, process-level storage independent of the render lifecycle.

2. Special staleTime during hydration

Inside $useQuery():

const sync = typeof options.meta?.persister === 'object' && options.meta?.persister?.sync;
if (sync !== true) {
  const staleTime = options.staleTime ?? this.scopeSelf.config.query.staleTime.async;
  const queryCache = this.$queryFind({ queryKey });
  const queryCacheExists = queryCache?.state.data !== undefined;
  options.staleTime = query => {
    if (!queryCacheExists) return resolveStaleTime(0, query);
    if (process.env.CLIENT && this.ctx.meta.$ssr.isRuntimeSsrPreHydration) {
      return resolveStaleTime(this.scopeSelf.config.query.staleTime.ssr, query);  // Infinity
    }
    return resolveStaleTime(staleTime, query);
  };
}
Enter fullscreen mode Exit fullscreen mode

staleTime.ssr defaults to Infinity — during hydration, queries restored from SSR dehydration are considered permanently fresh. The server just rendered them; the client has no reason to disbelieve. Only after hydration completes does normal staleTime.async (default 0, meaning immediately stale) kick in.

Next.js doesn't need this — the RSC Payload carries dataUpdatedAt timestamps and React Query handles freshness on its own.

3. Router Tabs persistence

This one is very practical. From tabs.ts:

@Model<IModelOptionsTabs>({ cache: false })
export class ModelTabs extends BeanModelBase {
  protected async __init__(scene: string, options?: ModelTabsOptions) {
    // ...
    if (this.tabsOptions.cache) {
      this._tabsState = this.$useStateLocalAsync(queryOptionsTabs);  // localStorage
      this._offPersistence = persistence.subscribe(() => {
        if (!this._tabsDisposed && !this.ctx.disposed) {
          this._startTabsRestore(this._getTabsReadiness());
        }
      });
    } else {
      this._tabsState = this.$useStateMem(queryOptionsTabs);  // in-memory only
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

With tabsOptions.cache: true, the tab list persists to localStorage. But persistence isn't directly consumed — persistence.subscribe() watches for scope changes and triggers a reload each time, ensuring tab state always aligns with the current identity.

Next.js Router Cache also caches route-segment state, but never across sessions and with no identity-aware auto-restore. Close and reopen the browser and your previously open tabs are gone.


7. The Essential Point

Reduce everything to one sentence:

Zova caches data state; Next.js caches rendered output.

Zova cares about:

  • "If the browser closes and reopens, do my orders still show up?"
  • "After logout, does the next account see stale data?"
  • "When switching workspaces, should the cache wipe?"

Next.js cares about:

  • "Is this route pre-rendered? Can I skip the server?"
  • "Can fetch results be reused across requests?"
  • "The CMS updated — which tag do I invalidate?"

The first is client-side architecture thinking — multi-tenant SPA state lifecycle management. The second is full-stack rendering framework thinking — reducing server work and making first paint faster.

These two models are not in conflict. In the same application you can have Zova's identity-aware persistence protecting user state on the client, while Next.js's ISR + revalidateTag protects rendered output on the server. They complement rather than compete.


8. Summary

  1. Zova's cache is a five-layer stack: memory → persistence → identity isolation → SSR HTTP → KeepAlive. The two most distinctive layers are persistence and identity isolation.
  2. The persistence layer implements PersistenceQueue + generation counters to prevent async race conditions. Three storage tiers (cookie / localStorage / IndexedDB) expire by maxAge.
  3. Identity isolation uses a scope triple plus epoch tokens. Any scope change auto-invalidates all DB-persisted queries and silently drops in-flight operations.
  4. SSR cache is two explicit profile tiers (public / session) with no auto-inference.
  5. Next.js caches are a four-layer stack built around render output reuse. TTL semantics are stale-while-revalidate, and trust in cache must be explicitly opted in.
  6. Defaults point in opposite directions: Zova trusts cache and minimizes requests; Next.js distrusts cache and requires opt-in.
  7. The two are not incompatible — they complement each other in a single application.

References and Source

Zova / Cabloy

Next.js

Top comments (0)