ISR and caching
Cache your content pages and revalidate them the moment content changes. Tag reads with nextlyTags/cachedFind and Nextly busts them on every write.
Nextly turns every content change into a cache invalidation. Tag a page's data
with the collection/entry it reads, and a create, update, publish, unpublish,
delete, or slug change busts exactly those tags — the page regenerates on the
next visit, with no rebuild and no force-dynamic.
This is Next.js Incremental Static Regeneration driven by your content, not a timer.
How it works
- A read tags its cached data with the
nextly:*tags for the collection (and, for a detail page, the entry id). - A write computes the same tags and, after it commits and before it
responds, expires each one, so any page tagged with them is invalidated.
In a Server Action it calls Next's
updateTag, so the person who made the change sees it on their next read. Everywhere else (a Route Handler, the admin API) it callsrevalidateTag(tag, { expire: 0 }).
The write side is automatic once the admin route is wired (see below). You only add the read-side tags.
Enable it
Register the adapter once per server process. The most reliable place is Next's
instrumentation.ts,
whose register() runs at startup, before any route, Server Action, or
serverless worker handles a request — so every write context busts tags,
not just the ones that happen to have loaded the admin route:
// src/instrumentation.ts in a project with a src/ directory (every scaffolded
// project); instrumentation.ts at the project root otherwise. Next.js ignores
// the file anywhere else, silently.
export async function register() {
// Node.js only: the adapter loads `next/cache` with `createRequire`, which
// the edge runtime does not have.
if (process.env.NEXT_RUNTIME === "nodejs") {
const { registerNextCacheRevalidator } = await import("nextly/runtime");
registerNextCacheRevalidator();
}
}Mounting the admin route handler also registers it, which is enough if every content write goes through the admin API in the same process:
// src/app/admin/api/[[...params]]/route.ts
import nextlyConfig from "../../../../../nextly.config";
import { createDynamicHandlers } from "nextly/runtime";
export const { GET, POST, PUT, PATCH, DELETE, OPTIONS } = createDynamicHandlers(
{
config: nextlyConfig,
}
);If you write content through the Direct API (nextly.create(...)) from a Server
Action, a custom route, or the admin API, register from instrumentation.ts as
above — relying on the admin route alone leaves those contexts on the no-op
revalidator, and their writes would not refresh cached pages. A write in a
context with no adapter registered is a silent no-op for revalidation (never an
error), so it is safe but stale.
Writes outside a request
Automatic revalidation fires for a write that runs inside a Next.js request or render — a Route Handler, a Server Action, or the admin API. That is where Next.js can expire a tag, and it covers how content is normally edited.
A write from outside a request — a cron job, a CLI, or a background worker
with no request in flight — cannot expire a tag through Next.js: it has no
cache scope to invalidate there. The write still succeeds, and Nextly records
its tags in the database, in a table nextly migrate creates:
- With Nextly's cache handlers installed (see Cache Components below), every instance reads that record and stops serving the previous version within about five seconds, whichever process made the write.
- Without them, Next.js's own cache never reads the record. A write made
in the app's own process is expired there with the next write that runs
inside a request, and Nextly logs one line per process the first time that
happens. A write from a separate process, such as the CLI or another
instance, does not reach the app's cache, so in production Nextly bounds
every cached public read: one older than 30 seconds is refreshed in the
background. The first visit past that gets the previous version once while
it refreshes, and the next gets the new one, so a write shows within a minute
of a visit. The
"use cache"read functioncreate-nextly-appwrites expires an entry after 5 minutes at the soonest, which is as soon as Next.js still keeps it in a static prerender, so it serves none older than that. Where the app registers no such function, the read is refreshed in the same way but not expired: after a quiet spell, the first read can still get the previous version once, however old, while it refreshes. Nextly logs onecache-handlers-not-sharedline per process when this bound is in force. To refresh pages straight away and keep longer lifetimes, install the handlers, or run the write in a Route Handler or a Server Action.
Several instances, and upgrading an app
Nextly's cache handlers need nothing beyond the database the app already uses. Each instance keeps its cached entries in its own memory, and every instance shares when each tag last expired through one table in that database. No Redis or other cache service is involved.
create-nextly-app installs them in every app it creates, and adds them when it
joins an existing app. It leaves the handler settings out, and prints the lines
to put in place, where the config already has a cache handler of its own, sets a
handler setting to undefined, or sets cacheMaxMemorySize to anything but
0. An app that keeps a handler of its own is served as an app without
Nextly's: writes made outside a request don't reach that handler, so its cached
public reads refresh within a minute of a visit in production.
To add them to an app by hand:
- Run
nextly migrate, which creates thenextly_cache_tag_expiriestable. Until it exists, Nextly warns once and each instance sees only the writes it makes itself. - Add the handler settings to
next.config.ts, as in step 2 of Cache Components below:cacheHandler,cacheMaxMemorySize: 0andcacheHandlers. - Deploy, load a page that reads content through Nextly on each instance, and
then check that instance's log. Nextly says
cache-handlers-not-sharedat the first cached read the handlers don't serve, so the line's absence means something only once such a read has run.
When the new version shows
- Server Action: the expiry completes before the action returns, and
updateTaglets the person who made the change read it straight away. - Route Handler and the admin API: the expiry starts before the response is sent and completes in the same invocation. With Nextly's cache handlers installed, a request made after the response arrives reads the new version. A request already in flight while the write ran may still read the previous one.
- Other instances: with Nextly's cache handlers installed (see Cache Components below), every other instance stops serving the previous version within about five seconds. They treat the expiry as standing for two seconds past the write, the time an instance may still hold a collection's settings from before a change, so a page one of them rebuilt from settings it read just before a schema change is not served either. Those two seconds are the whole cost: a tag written more than about once every two seconds keeps the other instances rebuilding the reads that carry it until the writes pause, while the instance making the writes is not affected.
- Without Nextly's cache handlers: Next.js's own cache judges a stored page
or read by when it was stored, not by when its render read the content. A
render stores its page after its response is sent, so a render that began
before a write and stored its page a few milliseconds after it is served as
fresh, with the previous content, until its lifetime runs out. Next.js's
cache also serves a page's previous version once after a write expires it.
Nextly's handlers judge each entry by when its render began and expire it at
once, which is why
create-nextly-appinstalls them.
If an expiry fails
A tag that fails to expire is retried once. If it fails again, the write still succeeds: Nextly logs the tags and expires them with the next write in a request, and the REST and admin response says so with a notice. If the database refuses the record that tells other instances, Nextly also retries that on its own: after 1 second, then waiting twice as long each time up to 30 seconds, and at the process's next cached read. Other instances then see the write within about a minute of the database answering again, and on serverless within a minute of the next invocation. It logs one line when these retries start and one when they succeed. The notice looks like this:
{
"warnings": [
{
"severity": "notice",
"phase": "cache-expiry",
"collection": "posts",
"code": "CACHE_EXPIRY_DEFERRED",
"message": "The change is saved. Its public pages may show the previous version for a while."
}
]
}The Direct API's mutations return the same notice in the result's warnings, so a caller can tell the expiry was deferred.
Which writes expire a page
Every write that changes what a read returns:
- creating, updating, publishing, unpublishing and deleting an entry, and a slug change;
- saving a Single;
- a release that publishes or unpublishes its documents;
- deleting a collection or a Single;
- a plugin writing to columns it added to a collection, a Single or a component
with
ctx.db.contributed(...).set. A component's row expires the entry or Single it sits in. Insidectx.db.transactionthe expiry waits for the commit, and a rolled-back write expires nothing.
Tag a read
Use cachedFind to cache a data read and nextlyTags to tag it:
// app/(site)/blog/[slug]/page.tsx
import { getNextly } from "nextly";
import { cachedFind, nextlyTags } from "nextly/runtime";
import config from "../../../../nextly.config";
export default async function Post({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const nx = await getNextly({ config });
const post = await cachedFind(
async () => {
const { items } = await nx.find({
collection: "posts",
where: { slug: { equals: slug }, status: { equals: "published" } },
limit: 1,
});
return items[0] ?? null;
},
{ tags: nextlyTags("posts"), keyParts: ["posts", "detail", slug] }
);
if (!post) return null;
return <article>{/* ... */}</article>;
}Publishing or editing any post now busts nextly:posts and this page
regenerates. For a listing page, tag it the same way — nextlyTags("posts") —
and it revalidates on any change in the collection.
nextlyTags(collection, id?, locale?)
Builds the tags a read should carry:
nextlyTags("posts")— the collection tag; for lists, indexes, sitemaps.nextlyTags("posts", id)— adds the entry-id tag; for a detail page, so a change to that one entry invalidates it. Tags by the immutable id, so a slug rename or a status change still invalidates.nextlyTags("posts", id, locale)— adds the per-locale id tag.
A detail read intentionally carries the collection tag too, so it also refreshes when the collection changes around it. Because a match on any tag invalidates the entry, that broadens invalidation: any change in the collection (or any locale of the entry) refreshes the read, rather than only that one locale's page. That is safe — a stale read is never served, only re-fetched more often. If you need strictly per-entry or per-locale granularity on a high-traffic route, tag with the entry/locale tag alone rather than this helper's broad, safe default.
entryIdTag(collection, id)
The entry-id tag alone, nextly:{collection}:id:{id}, without the collection
tag nextlyTags leads with: for a read that names one record and should refresh
when that record changes, not when any of its siblings do. Every write to the
entry expires it. The page builder tags the components and forms a page places
this way, so saving one refreshes only the pages that draw it. A form provider
names it through cacheTags
(Forms). It is exported
from nextly, nextly/runtime and @nextlyhq/plugin-sdk, and is experimental.
For a singleton (global) use nextlySingleTags("header").
Security: caching a per-user read
cachedFind's keyParts decide which requests share a cache entry. Include
anything the result varies by — and for a read that applies per-caller access
rules (a code-defined access.read that reads the caller's roles or
permissions, an API key's narrowed scope), that means the caller's identity:
// Per-user list — the caller's id is in the key, so it never leaks.
declare const user: import("nextly").UserContext;
// `nx` is the instance the page obtains above, inside its own component. Each
// fence here stands alone, so it is declared rather than assumed in scope.
declare const nx: Awaited<ReturnType<typeof import("nextly").getNextly>>;
const mine = await cachedFind(() => nx.find({ collection: "orders", user }), {
tags: nextlyTags("orders"),
keyParts: ["orders", "list", user.id], // <-- caller identity
});If you cache an owner-filtered read under a stable key that omits the caller, two different users share one cache entry and one is served the other's rows — a cross-tenant data leak, not a stale-cache annoyance. For genuinely public content (the same for every reader, like a published blog post) a stable key is correct and gives the full caching benefit.
Opt out of revalidation
A collection or Single whose pages manage their own freshness can opt out with
revalidate: { disable: true } in its config. None of the writes above then
expire its tags, a delete or a plugin's write included. One exception: when a
write cannot read the setting, because the record is already gone or the
registry cannot be reached, it expires the derived nextly:* tags anyway. An
extra cache miss is the cheaper mistake; a page left stale is the worse one.
A bulk import, seed, or CLI write that owns its own cache strategy can skip the
per-row revalidation with disableRevalidate:
await nx.create({ collection: "posts", data, disableRevalidate: true });The write still records its outbox event (webhooks and retention are unaffected); it just does not bust any cache tags.
Cache Components
Nextly runs with Cache Components and Partial Prefetching on. An app made by
create-nextly-app has both, and so does one it joins, unless that app's
config can't be changed safely: then the report prints the lines to add
(Installation). Three
things keep its cached reads fresh; with only some of them, a page read right
after a write can still show the previous version. A new blog has all three. An
app made by an earlier Nextly release, which turned Cache Components off, needs
each of them.
-
Read through the app's own
"use cache"function. Once Cache Components is on, Next.js caches non-fetch reads with"use cache"andcacheTag, and the directive works only in code Next.js compiles. A scaffolded blog keeps that function insrc/nextly/cached-read.ts. In a blog made by an earlier release that file is a stub that registers nothing: replace it with this. Where a copy of it made earlier has an expiry ofMath.max(revalidate * 2, 60), change the60to300: Next.js leaves an entry that expires within 5 minutes out of a static prerender, and a route that must be static, withensureStatic, then fails to build.// src/nextly/cached-read.ts import { cacheLife, cacheTag } from "next/cache"; import { getNextly, registerNextlyStart } from "nextly"; import { registerCachedRead, runRegisteredRead } from "nextly/runtime"; import config from "@nextly-config"; export async function cachedRead( key: string, tags: string[], revalidate: number | false ): Promise<unknown> { "use cache"; cacheTag(...tags); // `revalidate: false` is tag-only, as everywhere in Nextly: only a write // expires the entry, never time. Next.js's "max" profile revalidates monthly. if (revalidate === false) { cacheLife({ revalidate: Infinity, expire: Infinity }); } else { // Expired at twice the revalidate, and never within 5 minutes: Next.js // leaves an entry that expires sooner out of a static prerender. cacheLife({ revalidate, expire: Math.max(revalidate * 2, 300) }); } return runRegisteredRead(key); } registerCachedRead(cachedRead, process.env.__NEXT_CACHE_COMPONENTS); // Tells Nextly how this app starts it, for a read that finds it not started, // such as the root layout's `<SiteCode>` on `/_not-found` while `next build` // prerenders, where nothing else starts it. Nothing starts here: a page that // calls `getNextly` first is the start that counts. An app that passes // `getNextly` more than its config passes the same options here. registerNextlyStart(() => getNextly({ config }));Import the config the way your app already does:
@nextly-configin a scaffolded app, or a relative path tonextly.config.ts. If your app passesgetNextlymore than its config (its own adapter, logger or service overrides), pass the same options toregisterNextlyStart.Import this file from your root layout (
import "@/nextly/cached-read";). That one import registers the cached read, and how Nextly starts when a read finds it not started, on every route before anything reads,/_not-foundincluded. Nothing starts as the file loads: a page that callsgetNextlyfirst is the start that counts, and the registered start runs only for a read made before anything started Nextly, as on/_not-foundduringnext build, whereinstrumentation.tsdoes not run. A start that fails is tried again, with the same options, by the next read. Import it as well from every module that reads content throughcachedFind. A scaffolded app's root layout already does, and so do the blog's query modules (src/lib/queries). The page builder's<SiteCode>refuses to read without it, and names this file in its error (Site code). Nextly passes the function only the read's key, tags and lifetime, which"use cache"can cache, and runs the reader itself. Register it from a module Next.js compiles as a server component: a copy imported frominstrumentation.tsis not a cached function. A read withrevalidate: false, the default, is cached until a write expires one of its tags, as with Cache Components off; one with a number of seconds is served stale past it and refreshed in the background. Outside a request or build, in a script or a background job, the read runs directly, uncached. -
Install Nextly's cache handlers in
next.config.ts. Next.js's default incremental cache serves a page's previous shell once after its tags are expired, so the first read after a write would still be the old version. It also judges an entry by when it was stored, so a page whose render began before a write and was stored just after it stands as fresh (When the new version shows). Nextly's handlers judge each entry by when its render began:cacheComponents: true, partialPrefetching: true, cacheHandler: require.resolve("nextly/cache-handler"), cacheMaxMemorySize: 0, cacheHandlers: { default: require.resolve("nextly/cache-handlers") }, -
Keep
createRegister'scacheComponentsvalue ininstrumentation.ts(process.env.__NEXT_CACHE_COMPONENTS). Nextly, loaded fromnode_modules, learns the setting only from it: with it off, Nextly warns once at start; with it on and no read function registered, Nextly warns at the first cached read and keeps usingunstable_cache.
With Cache Components off, which Nextly does not support, Next.js refuses to
build a "use cache" function, so a blog with it off keeps only how Nextly
starts in this file: the nextly and config imports and the last line,
without cachedRead and its registration. Its reads are then cached with
unstable_cache.
Notes
- Works across the supported Next.js range (see
Requirements) on the stable
revalidateTag/unstable_cacheprimitives. cachedFindruns the reader directly (no caching) outside a Next runtime, so the same code works in tests and non-Next callers.- Add
revalidate: <seconds>tocachedFindfor a time-based safety net on top of tag-based busting. - Next.js keeps at most 128 tags on one cached read and drops any tag longer
than 256 characters.
cachedFindleaves out the over-long tags, keeps each tag once in the order you give, and leaves off any past 128 with a warning logged once. The routes Nextly provides put their own collection's or Single's tag first, so a read that lists many related collections still expires whenever its own content changes. A read that lists many related collections still expires whenever its own content changes.
Draft / Published Status
Enable a Draft / Published lifecycle on collections and singles, with side-by-side examples for code-first config and the Visual Schema Builder.
Routing and SEO
Turn content into pages with correct metadata, sitemap, and robots. The nextly/runtime helpers resolve a slug to a published, access-enforced entry, build a Next.js Metadata object from an seo field group, and deliver sitemap.xml and robots.txt.