Skip to content

Search tags, filters, functions and guides.

Tags / cache

Tags

cache

Save a section's output and reuse it in later renders.

cache saves the output of a section, so later renders reuse it instead of rendering the section again. Use it for parts that are slow to build, such as long lists or sections that load data.

{% cache ["post", post.id, post.updatedAt] for 600 %}
	<article>
		<h2>{{ post.title }}</h2>
		{{ post.body|raw }}
	</article>
{% endcache %}

When a render reaches the tag, Kiln looks for a saved copy under the key. If there is one, Kiln outputs it and runs nothing inside the tag. If there isn't, Kiln renders the section, outputs it and saves it.

Caching does nothing until you give the environment a cache store. Without one, the section renders every time, so the same templates work in development and tests. See Cache stores.

Keys

The key decides when a saved copy is reused, so include everything the output depends on. A key is a string, a number, a boolean, a date or null, or a list of these.

  • Put a version in the key, such as post.updatedAt. When the post changes, so does the key, and Kiln renders the section again. You never need to clear the cache.
  • Kiln adds the template's name and the render's locale and time zone to every key. Two templates can use the same key, and dates and numbers are never shown in the wrong language. Globals passed to one render are not added, so include any the section's output depends on.
  • Kiln also adds a short hash of the tag's content. Editing that source gives it new keys, and two tags in one template only share copies when their content is the same. The hash does not cover included templates, macros, block overrides, slot fills or your functions.
  • Never cache content for one visitor under a key that doesn't include them, or other visitors will see it.

Deployments and shared stores

Set cacheNamespace when cached output survives a deployment. Include your app's identity and a build version, and change the version whenever templates or rendering code change. Kiln includes the namespace in every cache key, so the new build cannot reuse output from the old one. Give separate apps or tenants separate namespaces when they share a store.

const kiln = createKiln({
	loader,
	cache,
	cacheNamespace: `website:${buildId}`,
});

The default namespace is an empty string. A namespace does not replace the tag's key: include visitor data and any other values that change between renders. If different pages override a block or fill a slot inside the same cached section, include their identity in the key too. invalidate clears compiled templates; it does not clear saved fragment output.

How long copies last

for sets the most seconds a copy is kept. Without it, the store decides.

{% cache "footer" for 3600 %}…{% endcache %}
{% cache "footer" %}…{% endcache %}

Tags

A key works when the template knows what the section depends on. When the data comes from your functions, they can say instead. A function wrapped in withRender can tag the cached section it runs in, and your store can clear every copy with a tag when that data changes.

import { createKiln, memoryCache, withRender } from "@lucidkiln/core";

const cache = memoryCache();

const kiln = createKiln({
	loader,
	cache,
	functions: {
		documents: withRender((render, collection: string) => {
			render.tagCache(`collection:${collection}`);
			return db.list(collection);
		}),
	},
});

// Later, when a document in "pages" changes:
cache.clear({ tags: ["collection:pages"] });
  • tagCache tags the innermost cached section the call runs in, and every cached section around it. Outside a cached section it does nothing.
  • Tags are strings. A section has each tag once, however many calls add it.
  • A saved copy keeps its tags. When a section uses a saved copy of a section inside it, it gets that section's tags too.
  • Tags don't change the key. They tell the store which copies to clear.

Scope

The section can read the variables around it. Variables set inside it stay inside it, even ones that already exist outside, so a saved copy leaves the same variables behind as a fresh render. That includes variables set by blocks the section places and by fills of components it renders.

If the section fails, nothing is saved.

Cache stores

Pass a store as the cache option. memoryCache keeps copies in memory, which suits a long-running Node server. It holds 1,000 copies by default and drops the oldest first. Its clear method removes copies: clear() removes all of them, and clear({ tags }) removes those with any of the tags.

import { createKiln, memoryCache } from "@lucidkiln/core";

const kiln = createKiln({ loader, cache: memoryCache({ max: 500 }) });

Any object with get and set methods is a store, so you can keep copies elsewhere, such as Workers KV:

const kiln = createKiln({
	loader,
	cache: {
		get: ({ key }) => env.KV.get(key),
		set: ({ key, value, seconds }) =>
			env.KV.put(key, value, seconds ? { expirationTtl: seconds } : {}),
	},
});
  • set({ key, value, seconds, tags, state }) saves a copy. value is a string Kiln makes, holding the HTML and anything the section added to an outlet. Save it as it is. seconds is the value of for, or null. tags lists the section's tags in sorted order, and is empty when it has none.
  • get({ key, state }) returns the saved value, or null when there is none.
  • state is the render's state option, for a store that keeps something per request, such as the connection it reads with.
  • To clear copies by tag, keep the tags with each copy. A store that can't list its copies, such as Workers KV, can keep a version for each tag instead: save the versions with the copy, change a tag's version to clear it, and have get return null when a saved version is out of date.
  • Both take one object, so Kiln can pass more details later without breaking your store.
  • Either may return a promise. The render only waits when one does.
  • If either throws or rejects, the render stops with a host-error. Its cause holds the original error.