Storage details
The drivers, options and limits behind the Storage and cache guide. The functions are in the hamur/server reference.
Mounts
useStorage(mount)gives a key-value store.- A mount is a name; the config says which driver backs it with a call from
hamur/storage, such asfs({ base: ".data/cache" }), whose options are typed, and a mount that the config does not name is kept in memory, exceptdata. - A mount written as
{ driver: "redis" }fails at load:storage.cache: { driver: "redis" } was removed; write redis({ … }) from "hamur/storage". datais a file store by default: without adatamount,useStorage("data")keeps its items in.data/kvunderhamur devand on thebun,nodeandstaticpresets (hamur initlists.data/in.gitignore). On other presets it is in memory and logs once per processstorage "data" is in memory on vercel; configure storage.data.- Keys are separated by
:;/and\separate them too, souser/1is the same key asuser:1. - A prefix matches whole segments:
getKeys("user")returnsuser,user:1anduser:2:x, notusers:1. - A segment that is
.,..or contains a NUL byte throws.
Metadata, counters and batches
getMeta(key)gives what the backend knows (mtimeandsizeonmemory,fs,sqlite,s3anddb;expires, in ms, where an expiry is stored) merged with the fieldssetMeta(key, { … })stored; a missing key gives{}.removeMeta(key)clears the fields. Custom fields are kept under<key>$with the item's expiry, so they end with the item.setMetaof a missing item throwsTypeError: storage "x": setMeta of "k" needs an existing item, and a key whose last segment ends in$is refused (Storage key "a$" ends in "$", which marks metadata).increment(key, by = 1, { ttl })adds an integer and gives the new value. A missing key starts at 0, andttlapplies only when this call creates the key, which makes a fixed window for a rate limit. It is atomic onmemory,sqlite,redis,dbandplanetscale; on every other driver it runs under a lock of this process and logs once per mountincrement on <driver> is not atomic across instances. Values and results must be safe integers.getItems(keys)gives{ key, value }in the given order,valueundefinedfor a missing key, andsetItems([{ key, value, options }])writes many (avalueofundefinedremoves the key). They are oneMGETonredis, one query onsqlite,dbandplanetscale, and the single calls together elsewhere; a refused key throws before anything is written.getKeys(prefix, { maxDepth })counts segments below the prefix:a:1anda:b:2underawithmaxDepth: 1givea:1.
import { createError, defineHandler, useStorage } from "hamur/server"
export const hit = defineHandler({
route: "/api/hit",
method: "POST",
async handler() {
const limits = useStorage("limits")
const count = await limits.increment("hits", 1, { ttl: 60 })
if (count > 100) throw createError({ status: 429, message: "Too many hits" })
await limits.setMeta("hits", { lastHit: new Date().toISOString() })
const items = await limits.getItems(["hits", "missing"])
return { count, meta: await limits.getMeta("hits"), values: items.map((item) => item.value) }
},
})
Watching changes
watch(callback)callscallback("update" | "remove", key)after every change made through this process (setItem,setItems,increment,setMeta,removeItem,clearonce per key) and gives the function that stops it.- The
fsdriver also reports files that another process changed, with a recursivefs.watchdebounced for 50 ms, and does not report its own writes twice. - A callback that throws is logged at
errorand does not stop the others.
import { definePlugin, useStorage } from "hamur/server"
export default definePlugin((server) => {
const unwatch = useStorage("content").watch((event, key) => {
console.log(`content ${event}: ${key}`)
})
server.hooks.hook("close", unwatch)
})
Snapshots
snapshot(storage, prefix?)reads every item at or below a prefix into an object andrestoreSnapshot(storage, data, prefix?)writes one back.- Keys are relative to the prefix, so a snapshot can move to another prefix or mount.
- Expired items are left out, and a TTL and metadata are not carried.
- Restoring adds to the storage and removes nothing.
import { restoreSnapshot, snapshot, useStorage } from "hamur/server"
export async function backup() {
const copy = await snapshot(useStorage("data"), "users")
await restoreSnapshot(useStorage("data"), copy, "users-backup")
return Object.keys(copy).length
}
Prefix views and typed keys
prefixStorage(storage, "users")is a fullStoragewhose keys are relative tousers::getKeys()strips the prefix,clear()clears only below it, and a key cannot leave the view with...useStorage<Schema>(name)takes an object type from key patterns to value types;getItem,setItem,getItemsandsetItemsare then typed by key, a literal key that matches no pattern failstsc, andprefixStoragekeeps the schema.
import { prefixStorage, useStorage } from "hamur/server"
interface User {
name: string
joined: Date
}
interface Schema {
[key: `user:${string}`]: User
visits: number
}
export async function demo() {
const data = useStorage<Schema>("data")
await data.setItem("user:1", { name: "Ada", joined: new Date() })
await data.setItem("visits", 1)
const users = prefixStorage(data, "user")
return users.getItem("1")
}
Development-only mounts
devStoragereplaces thestoragemount of the same name, options and all, underhamur devand in the prerender of every preset.- A
$development.storageblock applies first, thendevStorageon top;devStorageis the key that also covers the prerender, where a platform driver such ascloudflare-kvcannot run. - A mount replaced this way imports no driver and opens no connection.
- The build checks
storagedrivers against the preset, notdevStoragedrivers, and a Cloudflare bundle carries nodevStoragedriver.
Mounting at run time and custom drivers
mountStorage(name, driver)replaces a mount of the same name, andunmountStorage(name)removes one and waits for its driver'sdispose(); after it,useStorage(name)is the default mount for that name: a fresh memory mount, or fordatathe.data/kvfile store onbun,nodeandstatic.- Calls already running finish first, a
Storageyou kept refuses new calls (storage "x" was unmounted; call useStorage("x") for the current mount), and the drain disposes every driver once.
import { definePlugin, mountStorage, useStorage } from "hamur/server"
import { mapDriver } from "./storage-mount-driver.ts"
export default definePlugin(async () => {
mountStorage("scratch", mapDriver({ label: "scratch" }))
await useStorage("scratch").setItem("started", Date.now())
})
- A driver is an object of functions over bytes:
getItem,setItem(key, value, expires?),hasItem,removeItem,getKeys(prefix)andclear(prefix), and optionallygetItems,setItems,getMeta,increment,watchanddispose. - A driver that leaves the optional ones out gets the fallbacks.
- A prefix ending in
:matches only keys that start with it. implementStorageDriverofhamur/servertypes a factory and gives it back as it is:
import { implementStorageDriver } from "hamur/server"
export const mapDriver = implementStorageDriver((options: { label?: string } = {}) => {
const items = new Map<string, { value: Uint8Array; expires?: number }>()
const live = (key: string) => {
const item = items.get(key)
if (item?.expires !== undefined && item.expires <= Date.now()) return undefined
return item
}
const under = (prefix: string, key: string) =>
!prefix || key === prefix || key.startsWith(prefix.endsWith(":") ? prefix : `${prefix}:`)
return {
async getItem(key) {
return live(key)?.value
},
async setItem(key, value, expires) {
items.set(key, { value, expires })
},
async hasItem(key) {
return live(key) !== undefined
},
async removeItem(key) {
items.delete(key)
},
async getKeys(prefix) {
return [...items.keys()].filter((key) => live(key) && under(prefix, key))
},
async clear(prefix) {
for (const key of [...items.keys()]) if (under(prefix, key)) items.delete(key)
},
dispose() {
items.clear()
console.log(`${options.label ?? "map"} driver disposed`)
},
}
})
- A driver in a file or a package is mounted through
defineStorageDriverofhamur/storage: it takesdriver, a path relative to the config file (./server/drivers/mine.ts) or a package whose default export is a factory(options, mount) => StorageDriver, andpresets, the presets it runs on, and gives the mount function, typed by its options type. - The build bundles the driver, a package with the preset's export conditions, and fails on a preset the list does not name.
- A driver that does not resolve fails the build (
Cannot find storage driver "./x.ts" for mount "y"), and one whose default export is not a function stops the server at start. - A module ships its driver the same way, as a function users call in their config.
Drivers
| Function | Runs on | Options |
|---|---|---|
memory() | every preset | max, the most entries held, and maxBytes, the most bytes held across all values, both positive integers; the oldest writes go first and a value larger than maxBytes is not stored (the cache mount you do not configure holds 10000 entries and 100 MB); lost when the process ends |
fs() | bun, node, static | base (required), the directory; readOnly, noClear, ignore (see below) |
sqlite() | bun, static | path (required), table |
redis() | bun, node, cloudflare, static | url, base (a key prefix) |
s3() | every preset | bucket, region, endpoint, accessKeyId, secretAccessKey, sessionToken, virtualHostedStyle, base |
cloudflareKV() | cloudflare | binding (required), base |
cloudflareR2() | cloudflare | binding (required), base (a key prefix) |
cloudflareCache() | cloudflare | name (for caches.open; default caches.default) |
netlifyBlobs() | netlify | name (required), deployScoped |
vercelBlob() | vercel | base (a key prefix) |
azureBlob() | every preset | accountName, containerName (required), accountKey or sasToken, base, endpoint |
planetscale() | every preset | url (required, with credentials), table |
vercelRuntimeCache() | vercel | none |
overlay() | every preset | layers, a list of mount configs, topmost first (see below) |
nullDriver() | every preset | none |
github() | every preset | repo (required, owner/name), branch (default main), dir, token, ttl (seconds the file list is cached, default 600); read-only |
http() | every preset | base (required), the absolute URL of a createStorageHandler route; headers, sent with every request |
dbStorage() of @hamur/db/storage | every preset the connection's connector runs on | connection (default default), table (default hamur_storage); needs the @hamur/db module, see Database |
defineStorageDriver | its presets | the factory's own, see above |
staticruns the server on Bun while it builds, to prerender, so it takes whatbuntakes.- A mount whose driver the preset cannot run is a build error that names the mount. On
vercelandnetlifythememorydriver is per function instance;s3,netlify-blobs(on Netlify),vercel-blobandvercel-runtime-cache(on Vercel) are shared.
fs
fstakes three more options.- With
readOnly: true, a write, a removal orclearthrowsTypeError: storage "<mount>" is read-only; reads work. - With
noClear: true,cleardoes nothing. ignoreis a list of glob patterns, matched against the key with:read as/, so["tmp/**", "**/*.bak"]leavestmp:aandb:c.bakout ofgetKeys;getItemandhasItemstill find them.- The patterns understand
*(anything but/),?(one character),**(anything,/included;**/may match nothing),{a,b}(one of the alternatives) and\to take the next character literally. !and[...]are ordinary characters, names starting with a dot match like any other, and matching is case-sensitive on every system.
overlay
- The
overlaydriver stacks mounts. layersis a list of mounts, each a driver call with its own options, and each is bundled and checked against the preset like a mount of its own.- A read tries the layers in order and takes the first value it finds.
- A write goes to the first layer only.
removeItemwrites a marker in the first layer, so the key reads as missing even though a lower layer still holds it, and the lower layer is not touched;cleardoes the same for every key it holds under the prefix. This puts a writable layer over files you ship:
import { defineConfig } from "hamur"
import { fs, overlay } from "hamur/storage"
export default defineConfig({
framework: "react",
storage: {
content: overlay({
layers: [fs({ base: ".data/content" }), fs({ base: "content", readOnly: true })],
}),
},
})
null
The null driver drops every write and reads as empty, so storage: { cache: nullDriver() } turns the cache off: a cached handler runs on every request.
github
- The
githubdriver reads the files of a repository, so a mount can serve content that lives in Git:storage: { docs: github({ repo: "acme/site", dir: "content", token: env("GITHUB_TOKEN") }) }. The patha/b/c.jsonis the keya:b:c.json. It lists the files with one call to the GitHub API and keeps the list forttlseconds, so a new commit shows after that long; a file is fetched when you read it. - Without a
tokenGitHub allows 60 requests an hour per IP address, and a private repository is not found. - Files are read as server assets are:
getItemparses a.jsonfile, gives other text files (.md,.txt,.yaml, …) as a string and any other file as bytes, andgetItemRawgives the bytes of any file. - A read gets the file of the commit the list came from, even if the branch has moved since.
dirmakes the API list only that directory.- A symlink, a submodule, a file whose name ends in
$and one whose name has a:or\are not listed. getMetahas thesizeand nomtime.- Every write,
removeItemandclearthrowsTypeError: github driver is read-only. - A repository with more than 100000 files, or a list over 7 MB, fails with
github tree of "owner/name" at "main" is truncated by the API, and a rate limit withgithub rate limit exceededand the time to try again.
redis, s3 and cloudflare-kv
- The
redisdriver usesurl(redis://orrediss://for TLS), elseVALKEY_URLorREDIS_URL, elselocalhost:6379. Onbunit usesBun.redis; onnodeandcloudflareit uses a client of Hamur's own overnode:net/node:tlsandcloudflare:sockets, with the same commands, so a mount behaves the same on all three. - The connection is made at the first use.
- A command sent on a connection that drops is rejected, never repeated; the next command opens a new connection. On Cloudflare each request opens its own socket.
- The variables come from
process.envon node and from the Worker'senvon cloudflare. - The
s3driver reads what you leave out from theS3_*andAWS_*variables. It runs on every preset: Bun's client onbun, and a SigV4 signer of Hamur's overfetcheverywhere else. - An item is an object
<base><key>that holds its expiry in front of the bytes, so it is not a plain file; use@hamur/blobfor files, and presigned URLs, which a storage value cannot be. Forcloudflare-kv,bindingis the name of akv_namespacesentry in the Worker configuration. - Put that entry in a
wrangler.jsonorwrangler.jsoncin the app root, not in.output/wrangler.json: every build rewrites that file, and an edit there is lost. - The build merges the root file into it; see Deploy.
The entry in wrangler.jsonc for a cloudflare-kv mount:
{
"name": "my-app",
"kv_namespaces": [{ "binding": "CACHE", "id": "<namespace id>" }],
"vars": { "ENVIRONMENT": "production" },
}
netlify-blobs
- The
netlify-blobsdriver talks to the Netlify Blobs HTTP API with the site'sNETLIFY_BLOBS_CONTEXT, which Netlify sets for functions; without it the first use fails withnetlify-blobs needs NETLIFY_BLOBS_CONTEXT (runs on Netlify). nameis the store's name (at most 64 bytes, no/); withdeployScopedthe items belong to the current deploy and a new deploy does not see them.- A key is at most 599 bytes.
- Reads go to the uncached edge when the context has one, so a written item is read back at once.
- A 429 or 5xx answer is retried up to five times.
- Expired items are not deleted on read, as on
cloudflare-r2, andincrementis not atomic across function instances.
cloudflare-r2 and cloudflare-cache
- For
cloudflare-r2,bindingis the name of anr2_bucketsentry in the Worker configuration, kept in the app root like the KV one; a missing binding fails the first read or write with its name. Each item is one object,<base><key>. - The
cloudflare-cachedriver keeps items in the Cloudflare Cache API: one cache per data center, so a value written in one region is not read in another, and the Cache API works only on a custom domain, not onworkers.dev. It can evict an item before itsttl. - It cannot list keys:
getKeysandclearthrowTypeError: cloudflare-cache cannot list keys. Use it for caches, not for data you need back.
planetscale
- The
planetscaledriver talks to PlanetScale's HTTP SQL API withfetch, so it runs wherever your server does. urlishttps://<username>:<password>@<host>or themysql://<username>:<password>@<host>string PlanetScale shows for a password (http://is accepted only forlocalhost); keep it in an environment variable, not in the config file.- Items live in one table,
hamur_storageunlesstablesays otherwise, created at first use: give eachplanetscalemount its own table. - A branch with safe migrations refuses that
CREATE TABLE; create the table through a deploy request (key VARBINARY(1024) NOT NULL PRIMARY KEY,value LONGBLOB NOT NULL,expires BIGINT,mtime BIGINT) and the driver uses it. - A key is at most 1023 bytes and a value at most 30 MiB: a larger one throws
planetscale storage value of key … is too large, naming the limit. incrementis atomic across instances: it runs in a transaction under the row's lock, in five requests.- The API takes no parameters, so the driver writes keys and values as hex literals; nothing you store can change the statement.
- A failed request throws
PlanetScale query failed: <the API's message>, never with the url or the password.
vercel-blob and vercel-runtime-cache
- On Vercel,
vercel-blobreadsBLOB_READ_WRITE_TOKEN, which Vercel sets when a Blob store is connected to the project, and keeps one private blob per item at<base><key>, read from the origin so a read sees the last write. It has noaccessoption: a public blob is served from a CDN cache that cannot be bypassed, so a mount could read an old value. - Use
@hamur/blobfor public files. vercel-runtime-cachekeeps items in the Vercel Runtime Cache of the function's region.- Vercel can evict an item before its
ttl, and it cannot list keys:getKeysandclearthrowTypeError: vercel-runtime-cache cannot list keys. - Outside a Vercel Function it throws
vercel-runtime-cache runs only on Vercel Functions. - Mounts on
vercel-runtime-cacheshare one cache, so give a key a prefix of its own when two mounts use it.
http
- The
httpdriver reads and writes a mount of another app over HTTP. That app serves the mount withcreateStorageHandler(mount, { authorize })fromhamur/serverin a raw handler on a catch-all route, andauthorizedecides who may read and who may write: throw to refuse, acreateError({ status: 403 })to answer that status, anything else answers 401, and returningfalseanswers 403. - It also learns whether a request is for one item or for everything below a prefix (
prefix: true), so a rule for one key does not open the keys below it. On a case-insensitive file system (macOS, Windows) thefsdriver keepsSECRETandsecretin one file, so with anfsmount there, writeauthorizerules that do not depend on case, such as comparingkey.toLowerCase(). - The driver sends
headerswith every request, so a token goes there. - Values travel as the stored bytes with their expiry in
x-hamur-expires, so attlset through the driver ends at the same time on the other side, and metadata works as on a local mount. Both apps' clocks must agree, since the expiry is an absolute time. - A refused or failed request throws
http storage: GET "a:b" failed with 401 Unauthorized; the headers are never in the message, and a page that hits it answers 500, not the remote's 401. - Redirects are not followed, so the headers never go to another host.
incrementis not atomic across instances on this driver.- The protocol is in the API reference.
import { createError, createStorageHandler, defineHandler, useRuntimeConfig } from "hamur/server"
const storageHandler = createStorageHandler("shared", {
authorize(event) {
const token = (useRuntimeConfig(event) as { storageToken?: string }).storageToken
if (!token || event.request.headers.get("authorization") !== `Bearer ${token}`) throw createError({ status: 401 })
},
})
export const storage = defineHandler({
method: "*",
route: "/_storage/**:key?",
raw: true,
handler: ({ key }: { key?: string[] }, { event }) => storageHandler(event, key),
})
import { defineConfig } from "hamur"
import { http } from "hamur/storage"
export default defineConfig({
framework: "react",
storage: {
shared: http({
base: "https://data.example.com/_storage",
headers: { authorization: `Bearer ${process.env.STORAGE_TOKEN}` },
}),
},
})
azure-blob
azure-blobkeeps one block blob per item at<base><key>in a container that already exists, over the Blob REST API withfetch, so it runs on every preset. GiveaccountName,containerNameand eitheraccountKey(the base64 key, signed with Shared Key bycrypto.subtle) orsasToken;AZURE_STORAGE_ACCOUNT,AZURE_STORAGE_KEYandAZURE_STORAGE_SAS_TOKENfill what the config leaves out.endpointpoints the driver at Azurite (http://127.0.0.1:10000/devstoreaccount1) or a sovereign cloud.- A refused request throws
Azure Blob GET <container>/<blob> failed: 403 AuthenticationFailed: …with the service's code and message. - Table, Cosmos DB, Key Vault and App Configuration have no built-in driver: write one with
implementStorageDriverand mount it withdefineStorageDriverofhamur/storage(see the server API reference,mountStorage,unmountStorage,implementStorageDriver).
Expired items
- An expired item reads as missing.
- The
fs,s3,cloudflare-r2,vercel-blobandazure-blobdrivers do not delete it when it is read, so it stays until you write the key again, callremoveItemorclear, or (on S3 and R2) a lifecycle rule on the bucket removes it. cloudflare-kvasks KV to expire every item with attl, but not sooner than 60 seconds ahead.
Secrets and encrypt
- Any option of a mount can be read from the env instead of the config file:
password: env("REDIS_PASSWORD"). - Declare
REDIS_PASSWORDinapp/env.tsand set it where the server runs; a nameapp/env.tsdoes not declare fails at load withstorage.cache.password reads env "REDIS_PASSWORD", which app/env.ts does not declare, and the old form{ runtimeConfig: "redisPassword" }withstorage.cache.password: { runtimeConfig } was removed; write env("NAME"). - The value is the one the server read at start (on Cloudflare, when the worker module loaded), after the entry's schema, so
default: ""gives""and a number schema a number. - A missing value fails the mount's first use with
storage "cache" option password reads env "REDIS_PASSWORD", which is not set.
encrypt: env("STORAGE_KEY") on a mount seals every value, raw values included, with AES-GCM before the driver sees it:
import { defineConfig, env } from "hamur"
import { redis } from "hamur/storage"
export default defineConfig({
framework: "react",
storage: {
sessions: redis({ url: env("REDIS_URL"), encrypt: env("STORAGE_KEY") }),
},
})
- The key is a string of at least 32 characters, or a list of up to 8 for rotation, which the entry's schema gives (
schema: (raw) => JSON.parse(raw ?? "")withSTORAGE_KEY='["new…","old…"]'): the first one seals new writes and every one opens, so you add the new key in front, and drop the old one once its values are rewritten. - A missing or short key fails the mount's first use with
storage "sessions" encrypt needs env "STORAGE_KEY" (at least 32 characters). - A value that does not open, because it was changed, written without the key, copied from another key or another mount, or sealed with a key you removed, reads as
undefined, and the first one per mount logs a warning. encryptgoes on the mount, not on an overlay layer (that is a config error), and a driver that reads files, such asgithub, cannot be encrypted.incrementon an encrypted mount reads, adds and writes the value again, so it is not atomic across instances on any driver.createStorageHandlerserves an encrypted mount's stored bytes, that is the ciphertext.- What
encryptdoes not protect: keys, expiry times,setMetafields, and whether an item exists and how large it is are stored in plain and are not authenticated. - Someone who can write to the store can change an item's expiry or metadata without it being noticed, and can put back an older sealed value of the same key, which still opens. Keep secrets in the value, not in metadata, and when an expiry or a version matters (a session), store it inside the value too and check it when you read.
Server assets
- Files a server reads and never serves by URL go in
server/assets/of the app and its layers (the app's file wins by path). They are the read-only mountuseStorage("assets:server"); a module addsassets:<name>withaddServerAssets. - A path becomes a key with
/turned into:, soserver/assets/data/a.jsonisdata:a.json. getItemparses a.jsonfile, gives other text files as a string and anything else as bytes,getItemRawgives the bytes, andgetMetagivessizeandmtime.- A write throws
TypeError: assets:server is read-only, and astoragemount namedassets:…fails at load. - On
bun,node,vercelandnetlifya file up to 1 MB is inlined in the bundle and a larger one is copied next to it. Oncloudflareevery file is inlined, because the assets binding serves public files and a server asset there would be public; the build warns when the assets pass 32 MiB, half of the 64 MiB a Worker may be. readAsset(url)fromhamur/serverreads an imported asset URL as aResponse.
KV and cache as mounts
NuxtHub's kv and cache are two storages. In Hamur each is a mount: name it in storage, keep a cheap driver for development in devStorage, and call useStorage.
import { defineConfig } from "hamur"
import { cloudflareKV, fs, memory } from "hamur/storage"
export default defineConfig({
framework: "react",
storage: {
kv: cloudflareKV({ binding: "KV" }),
cache: cloudflareKV({ binding: "CACHE" }),
},
devStorage: {
kv: fs({ base: ".data/kv" }),
cache: memory(),
},
})
import { defineCachedFunction, defineHandler, useStorage } from "hamur/server"
const price = defineCachedFunction(async (sku: string) => ({ sku, cents: 1999 }), { maxAge: 60, base: "cache" })
export const prices = defineHandler({
route: "/api/prices/:sku",
method: "GET",
async handler({ sku }: { sku: string }) {
const kv = useStorage("kv")
await kv.setItem(`seen:${sku}`, true, { ttl: 3600 })
return price(sku)
},
})
| NuxtHub | Hamur |
|---|---|
hubKV().get(key) | useStorage("kv").getItem(key) |
hubKV().set(key, value, { ttl }) | useStorage("kv").setItem(key, value, { ttl }), ttl in seconds, positive |
hubKV().has(key), .del(key) | hasItem(key), removeItem(key) |
hubKV().keys(prefix), .clear(prefix) | getKeys(prefix), clear(prefix) |
hubCache(), cached functions and handlers | defineCachedFunction, cache on a GET handler, or a route rule's cache; they keep entries in the cache mount, or in a mount per kind, see Where entries live |
cloudflare-kvneeds akv_namespacesentry for eachbindingin yourwrangler.json, or a namespace id the build can write (Deploy).- KV does not expire an item sooner than 60 seconds ahead; Hamur still ends the item at its exact time when it reads it.
MongoDB
There is no built-in MongoDB driver, and none is needed: a driver is one file over your own mongodb package. This one stores an item per document with the key as _id, and lets MongoDB's TTL index delete expired items:
import { Binary, MongoClient } from "mongodb"
import { implementStorageDriver } from "hamur/server"
interface Entry {
_id: string
value: Binary
expiresAt: Date | null
}
const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
export default implementStorageDriver((options: { url: string; database: string; collection?: string }) => {
const client = new MongoClient(options.url)
let ready: ReturnType<typeof open> | undefined
const open = async () => {
const collection = client.db(options.database).collection<Entry>(options.collection ?? "hamur_storage")
await collection.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })
return collection
}
const entries = () => (ready ??= open())
const live = { $or: [{ expiresAt: null }, { expiresAt: { $gt: new Date() } }] }
const under = (prefix: string) =>
!prefix
? {}
: prefix.endsWith(":")
? { _id: { $regex: `^${escape(prefix)}` } }
: { $or: [{ _id: prefix }, { _id: { $regex: `^${escape(prefix)}:` } }] }
return {
async getItem(key) {
const entry = await (await entries()).findOne({ _id: key, ...live })
return entry ? new Uint8Array(entry.value.buffer) : undefined
},
async setItem(key, value, expires) {
await (
await entries()
).replaceOne(
{ _id: key },
{ value: new Binary(value), expiresAt: expires ? new Date(expires) : null },
{ upsert: true },
)
},
async hasItem(key) {
return (await (await entries()).countDocuments({ _id: key, ...live }, { limit: 1 })) > 0
},
async removeItem(key) {
await (await entries()).deleteOne({ _id: key })
},
async getKeys(prefix) {
const found = await (await entries()).find({ $and: [live, under(prefix)] }, { projection: { _id: 1 } }).toArray()
return found.map((entry) => entry._id)
},
async clear(prefix) {
await (await entries()).deleteMany(under(prefix))
},
dispose: () => client.close(),
}
})
import { defineConfig, env } from "hamur"
import { defineStorageDriver, fs, memory } from "hamur/storage"
const mongodb = defineStorageDriver<{ url: string; database: string }>({
driver: "./server/drivers/mongodb.ts",
presets: ["bun", "node"],
})
const uploadthing = defineStorageDriver({
driver: "./server/drivers/uploadthing.ts",
presets: ["bun", "node", "vercel"],
})
export default defineConfig({
framework: "react",
storage: {
notes: mongodb({ url: env("MONGO_URL"), database: "app" }),
files: uploadthing({}),
},
devStorage: {
notes: fs({ base: ".data/notes" }),
files: memory(),
},
})
- The
mongodbpackage is your app's dependency, not Hamur's. defineStorageDriverlistsbunandnode, the presets that can open the connection, so a build for another preset fails;devStorageswaps it forfswhile you develop.disposecloses the client when the mount is replaced or the server drains.- Without
incrementthe driver gets the generic one, which is not atomic across instances.
UploadThing
The same shape works for UploadThing, with its UTApi from the uploadthing package. A mount maps a key to a file with that key as its customId:
import { UTApi, UTFile } from "uploadthing/server"
import { implementStorageDriver } from "hamur/server"
export default implementStorageDriver((options: { token?: string }) => {
const api = new UTApi({ token: options.token })
const urlOf = async (key: string) => (await api.getFileUrls(key, { keyType: "customId" })).data[0]?.url
const everyKey = async () => {
const keys: string[] = []
for (let offset = 0; ; offset += 500) {
const { files, hasMore } = await api.listFiles({ limit: 500, offset })
for (const file of files) if (file.customId && file.status === "Uploaded") keys.push(file.customId)
if (!hasMore) return keys
}
}
const under = (prefix: string, keys: string[]) =>
keys.filter((key) => !prefix || key === prefix || key.startsWith(prefix.endsWith(":") ? prefix : `${prefix}:`))
return {
async getItem(key) {
const url = await urlOf(key)
const response = url ? await fetch(url) : undefined
return response?.ok ? new Uint8Array(await response.arrayBuffer()) : undefined
},
async setItem(key, value, expires) {
if (expires) throw new TypeError("The UploadThing driver keeps files without an expiry; do not pass a ttl")
await api.deleteFiles(key, { keyType: "customId" })
await api.uploadFiles(new UTFile([value as BlobPart], key, { customId: key }))
},
async hasItem(key) {
return (await urlOf(key)) !== undefined
},
async removeItem(key) {
await api.deleteFiles(key, { keyType: "customId" })
},
async getKeys(prefix) {
return under(prefix, await everyKey())
},
async clear(prefix) {
const keys = under(prefix, await everyKey())
if (keys.length) await api.deleteFiles(keys, { keyType: "customId" })
},
}
})
- UploadThing does not expire files, so this driver refuses a
ttlwith aTypeError. It reads through the file's URL, so it suits few, large, rarely changed values. - The calls are typed by
uploadthing/server; run the driver against your account before you rely on how the service treats a missingcustomId. For user uploads,@hamur/blobwith a presigned or multipart upload is the better tool (Blob).
Cache
Caching and ISR is the guide to this section: tags, revalidation, isr on each preset and several instances.
- Three tools cache, and all keep their entries in storage, in the mount of their kind unless
basenames another; each kind usescacheuntil you mount its own (Where entries live). cacheon aGEThandler caches its answer. This is the way to cache a route or a call.defineCachedFunction(fn, options)caches what a function returns.- A route rule's
cacheorswron a route's path caches whatever that route answers, aResponseincluded: a feed, an image, arawroute. Thecacheof a handler stores only a value it returns, and refusesraw.
import { defineHandler } from "hamur/server"
export const prices = defineHandler({
route: "/prices",
method: "GET",
cache: { maxAge: 60, staleMaxAge: 600, varies: ["accept-language"] },
async handler() {
const response = await fetch("https://example.com/prices.json")
return (await response.json()) as Record<string, number>
},
})
A raw route that answers a Response is cached by a rule on its path:
import { cacheTag, defineHandler } from "hamur/server"
declare function renderFeed(): Promise<string>
export const feed = defineHandler({
route: "/feed.xml",
method: "GET",
raw: true,
async handler(_, { event }) {
cacheTag(event, "posts")
return new Response(await renderFeed(), { headers: { "content-type": "application/rss+xml" } })
},
})
import { defineConfig } from "hamur"
export default defineConfig({
framework: "react",
routeRules: {
"/feed.xml": { cache: { maxAge: 600, staleMaxAge: 3600, streamFill: true } },
},
})
| Option | Meaning |
|---|---|
maxAge | seconds an entry is fresh; required, and positive: 0 throws a TypeError |
swr | serve a stale entry at once and refresh it in the background; default true, and false for the cache of a handler |
staleMaxAge | seconds past maxAge a stale entry may still be served; without it, no limit |
getKey | the cache key; see below. The cache of a handler gets (input, event) and can only widen its own entries; a rule takes none |
varies | request header names whose values are part of the key (a handler's cache and rules only) |
maxResolveTime | seconds a fill may run; default 30; see Fill deadline |
staleIfError | seconds an entry past its stale window is still served when the fill that replaces it fails; see Serving stale on error |
base | the storage mount, the kind's mount by default (Where entries live), or a list of mounts, fastest first; see Tiers and versions |
integrity | a string that versions the entries in place of the function's source; see Tiers and versions |
getMaxAge | (entry) => seconds: the lifetime of one entry, read from its value; see Expiring and bypassing |
shouldBypassCache | (...args) => boolean: true skips the cache for this call |
shouldInvalidateCache | (...args) => boolean: true drops the entry before this call reads it |
validate | (entry) => boolean: false makes the entry a miss; see Checking and shaping entries |
transform, serialize, deserialize | cached functions only; see Checking and shaping entries |
maxEntrySize | bytes: route rules only; a larger answer is not stored; see Entry size |
streamFill | true: route rules only; the request that fills an entry gets the body as it streams; see Streaming fills |
- A fresh entry is returned as it is.
- A stale one is returned and refreshed once through
event.waitUntil. - Once it is too old, or missing, the caller waits for a new value.
- Several callers that miss on the same key share one call, and an error reaches all of them and is not stored.
- For a server route under a rule the key is the host, the path and the query, plus the values of the
variesheaders:a.test/x?q=1andb.test/x?q=1are two entries. - Only
GETandHEADare cached. - The handler runs on a cache fork, a copy of the request that carries only the
variesheaders and no client address. - A handler that reads the cookie or
authorization, as a session does, gets nothing unless those names are invaries; without them it always runs as an anonymous visitor. Itsevent.contextstarts empty, so what server middleware put there for the visitor (acontext.userread from the session) never reaches a stored answer. - A response is stored only when its status is 2xx (not 206), it sets no cookie, and its
cache-controlhas nono-store,no-cacheorprivate. - Other responses are sent to the caller that ran the handler and are not stored.
invalidateRouteCache(url)removes the entries a rule stored for an absolute URL, everyvariesvariant included, andinvalidate(...args)of a cached function removes the entry of those arguments.
Request memoization
Within one request a read asked twice runs once. Three readers are memoized, each for the life of the request only, so nothing is shared between requests or visitors:
| Reader | Memoized calls | Key |
|---|---|---|
the request-bound fetch: a load's ctx.fetch, useRequestFetch(), useApp().fetch on the server | GET and HEAD without a signal of their own and with a responseType other than "stream" | the method, the final URL (after baseURL and query) and the request headers the call sends, the forwarded cookie and authorization included |
an in-process call of a GET handler (a #server import a load or a handler calls) | every call | the handler and its serialized input |
memo(fn) | every call of the returned function | the wrapper and its serialized arguments |
- A parent and a child
loadthat both callgetUser()run it once. - A call that arrives while the same one runs joins it.
- A fetch caller gets its own
Responseof the one buffered answer, soresponseTypeand$fetch.rawwork per call; a handler ormemocaller gets the same value object as the first caller, and must not change it. - A rejection, and a fetch answer that is not 2xx, reaches every call that joined it and is then dropped, so the next call runs again.
- An in-process call of a handler that is not
GET, or a request-bound fetch call whose method is notGETorHEAD, clears the memo before it runs and again once it settles, andrefresh(event, fn, input)clears it too, so a read after a mutation in the same request sees the mutation, even when a parallelloadread while the mutation ran. - A cache fork has its own, empty memo: what it fills is shared by every request that waits on it, so it never reads one visitor's memo.
- Outside a request
memo(fn)callsfnevery time, and the global$fetchis not request-bound, so it memoizes nothing.
// server/users.ts
import { memo } from "hamur/server"
export const findUser = memo((id: number) => db.users.find(id))
Fetch cache
- On the server,
serverCachekeeps the answer of a$fetchGETorHEADcall in thecache:functionsmount (cachewhen it is not mounted), so later calls, from any request, skip the upstream until the entry is stale. It takesmaxAge,swr,staleMaxAge,profile,tags,maxResolveTime,staleIfErrorandvaries, resolved as every cache's:server.cache.defaults, then theprofile, then the fields. - Without a
maxAgefrom one of them the call throwsTypeError: $fetch serverCache needs maxAge, a profile or server.cache.defaults.maxAge. - The option is called
serverCachebecausecacheisfetch's own field. In the browser it is ignored, so a file shared with the client compiles and runs.
const rates = await $fetch("https://api.example.com/rates", {
query: { base: "EUR" },
headers: { "x-api-key": useRuntimeConfig().ratesKey },
serverCache: { maxAge: 300, tags: ["rates"] },
})
- What is stored is served to every visitor, so a
serverCachecall is anonymous: the request-bound fetch (ctx.fetch,useRequestFetch(),useApp().fetch) forwards nocookieorauthorizationof the visitor, and aset-cookiein its answer does not reach the page. - Headers the call sets are sent as they are and join the key only when
variesnames them. - A
cookieorauthorizationheader the call sets must be named invaries, so each value has its own entry; otherwise the call throws aTypeError. - A
fetch:requesthook still runs when the call reaches the upstream, but the key is read before it, so a hook that changes the URL, the method or a header of aserverCachecall makes the call throw aTypeError. - The key is the method, the final URL (after
baseURLandquery; an in-process URL on the request's origin, so each host has its own entries) and the values of thevariesheaders, stored asfetch:<sha256>. - A body larger than the entry cap (
server.cache.defaults.maxEntrySize, else half themaxBytesof amemorymount that holds it) is answered live and not stored. - One caller aborting does not stop the call others wait on, and the tags of the caches an in-process handler reads join the entry, so
revalidateTagof them reaches it. - Only a 2xx answer other than 206, without
set-cookieand withoutno-store,no-cacheorprivatein itscache-control, is stored; any other answer reaches its caller, aFetchErrorincluded, and the next call runs again. Each caller gets its ownResponseof the stored bytes, soresponseTypeapplies after the cache. revalidateTagreaches the entry through itstags, and an in-process URL also carries the implicitpath:tag, sorevalidatePath("/api/rates")reaches$fetch("/api/rates", { serverCache }).- A draft request skips the cache.
- Within one request the call is memoized like any
GET. $fetch.create({ serverCache })sets a default for a client; a call'sserverCache: falseturns it off. Another method ignoresserverCache.
Entry size
maxEntrySize(bytes, a positive integer) caps one stored answer. It defaults to half themaxBytesof thememorymount that holds the entries (50 MB of the defaultcachemount's 100 MB), and there is no cap on another driver.- An answer whose
content-lengthis larger goes to its request without being read for the cache. - An answer without one, or with a smaller one, is read while it is counted; once it passes the cap, the bytes read so far and the rest of the stream go to the client unchanged, and nothing is stored.
- Requests that waited for the same fill run the handler themselves, as after any answer that cannot be stored, and an older entry of that key is dropped.
- Nothing is logged. It is a cache option,
routeRules[...].cache.maxEntrySizeandserver.cache.defaults.maxEntrySize; it is notserver.maxBodySize, which limits request bodies. - A value that is not a positive integer is a config error.
Streaming fills
- By default the request that misses waits until the whole body is read, so a page that streams its HTML reaches that visitor only once it ends.
- With
streamFill: true(routeRules[...].cache.streamFill), that request gets each chunk as the handler writes it, and the same chunks are kept for the entry, which is stored when the body ends.
routeRules: { "/report": { cache: { maxAge: 300, streamFill: true } } }
- Requests for the same key that arrive during the fill wait for the stored entry, as they do without
streamFill, and the handler runs once. - A body that errors stores nothing: the filling request's stream errors, and the requests that waited run the handler themselves.
- A body that passes
maxEntrySizestops being kept at that chunk: the client still gets the whole stream, and the requests that waited run the handler at once. - Passing the fill deadline stores nothing and leaves the client's stream open; the requests that waited get the 504.
- The streamed answer carries no
etagorlast-modifiedthe cache computes from the body, since the headers are sent before the body is known; it keeps the ones the handler set. The stored entry has both, so the next request gets them. - A client that disconnects does not stop the fill: the body is still read and stored.
- It applies to a
GETanswer whose body is a stream; a string, bytes or JSON value is already whole and is stored as before, and aHEADfill and a background refresh of a stale entry read the body as before.
A value that is not a boolean is a config error: routeRules["/report"].cache.streamFill must be a boolean (got "yes").
Where entries live
Each kind of entry has its own mount, and a kind you do not mount uses cache, so an app that configures only cache keeps every entry there:
| Mount | Holds |
|---|---|
cache:pages | the cache, swr and isr route rules of pages, server-only components and server islands |
cache:handlers | the route rules of server routes |
cache:functions | defineCachedFunction, the cache of a GET handler and $fetch serverCache |
cache:tags | the tag index that revalidateTag and revalidatePath write |
// hamur.config.ts
export default defineConfig({
storage: {
"cache:pages": fs({ base: ".data/pages" }),
"cache:functions": redis({ url: "redis://cache.internal:6379" }),
},
})
- A kind's mount is one the config or
mountStoragenames; a mount made at run time takes over fromcachewith the next call. useStorage("cache:pages")with no such mount gives an empty memory mount, as for any unknown name, and does not move the pages there.- A
baseoption, or a rule'scache.base, wins over the kind. invalidate,expire,resolveKeys,invalidateRouteCacheand the fills act on the kind's mount, andrevalidateTagoncache:tags, which reaches entries on every mount.- Entries a kind wrote to
cachestay there when you add its mount later, and are no longer read; clear them withuseStorage("cache").clear("handlers")(orfunctions,fetch) if the driver keeps them. - A backend that is not a key-value store is a storage driver (custom drivers): its
getItem,setItemwith an expiry andremoveItemare all a cache needs, andrevalidateTagwrites only the tag index. - A driver whose
getKeysorclearthrows, ascloudflare-cache's andvercel-runtime-cache's do, still serves entries and tag revalidation, whileinvalidateandexpireof a handler, which list the keys below its URL, throw that error.
Tiers and versions
basenames the mount the entries live in.- A list of mounts makes a multi-tier cache, fastest first: a small in-process memory mount in front of a shared Redis, for example. It is an option of every cache, and
routeRules[...].cache.basefor a rule.
// hamur.config.ts
export default defineConfig({
storage: {
"cache-mem": memory({ maxBytes: 20_000_000 }),
"cache-redis": redis({ url: "redis://cache.internal:6379" }),
},
routeRules: { "/blog/**": { cache: { maxAge: 300, base: ["cache-mem", "cache-redis"] } } },
})
const getPost = defineCachedFunction(
async function getPost(slug: string) {
return loadPost(slug)
},
{ maxAge: 300, base: ["cache-mem", "cache-redis"], integrity: "posts-v2" },
)
- A read takes the entry of the first mount that holds a valid one (its shape,
deserializeandvalidatepass). When that is not the first mount, the entry is written back to the mounts before it throughevent.waitUntil, with the storage time it has left, so the next read finds it in the fast one. An entry that is too old or whose tag was revalidated is not written back; the new fill writes every mount. - A fill writes every mount, and an unstorable refresh removes the entry from every mount.
invalidate,expire,shouldInvalidateCacheandinvalidateRouteCacheact on every mount. A write-back that read the entry before one of them began, or while one was running, is dropped, so a removed or expired entry never comes back from a slower mount.- Tags have one index for all the mounts, so
revalidateTagandrevalidatePathreach the entry in each of them. - A mount that fails to read is a
cacheerror and the next mount is read; one that fails to write is acacheerror and the others are still written.invalidateandexpireact on every mount even when one fails, then throw the first failure. - Without
maxEntrySize, the cap is half themaxBytesof the smallestmemorymount in the list. - The
isrseed marker of a prerendered path is kept in the last mount, so a new instance with an empty first mount does not put the build's answer back after aninvalidate. - A
basethat is not a mount name or a non-empty list of distinct names isTypeError: defineCachedFunction base must be a mount name or a non-empty array of distinct mount names (got []), and a config error for a rule. - Each storage key holds a short hash of the function's source, so a deploy that changes the function misses the entries the old code wrote, and one that does not keeps them.
integrityreplaces that source with a string of your own: changing it misses every older entry, and keeping it keeps the entries across edits that do not change what is cached. The key then holds the function's name in place of its source, so the function must be named (async function getPost(), not an arrow passed inline), and the name must be unique among the caches that share anintegrity: twogetPostfunctions withintegrity: "v2"share entries.- An anonymous function is
TypeError: defineCachedFunction integrity needs a named function: with integrity the name, not the source, tells caches apart, so it must be unique per integrity (got an anonymous function). - An empty or non-string value is
TypeError: defineCachedFunction integrity must be a non-empty string (got "").
Range requests
- A request with a
Rangeheader never reads or writes the cache, in thecacheof a handler and in thecacheandswrroute rules. - The handler runs on the real request and its answer (206, 200 or 416) goes out as it is, with no entry read, none written and no wait on a fill in progress.
- Without this a stored 200 would answer
Range: bytes=0-9with the whole body, and a stored 206 would be sent as the whole resource to later visitors. - A page answer to a
Rangerequest also gets no CDNCache-Control.
Fill deadline
- Callers that miss on the same key share one fill.
maxResolveTimeis the number of seconds that fill may run,30by default.- If the handler has not finished by then, every caller waiting for it gets a
HamurErrorwith status 504 and the messageCache fill timed out after 30s, nothing is stored, and the next request runs the handler again. - A value that arrives after the deadline is dropped.
- The request that the handler receives carries an abort signal for the deadline, so a handler that passes
event.request.signaltofetchstops at the deadline. defineCachedFunctionhas no request and only stops waiting.
import { defineHandler } from "hamur/server"
export const prices = defineHandler({
route: "/prices",
method: "GET",
cache: { maxAge: 60, maxResolveTime: 10 },
async handler() {
const response = await fetch("https://example.com/prices.json")
return (await response.json()) as Record<string, number>
},
})
0orInfinitywaits without a limit. Any other value that is not a non-negative number is aTypeErrorfor a handler'scacheand a config error for a route rule. On a route rule, set it incache(Configuration); a rule written asswr: 600uses the default.- A 504 in a background
swrrefresh is logged and the stale entry stays.
Serving stale on error
- When a background refresh throws or passes
maxResolveTime, the stale entry stays and keeps answering, and the error goes to theerrorhook as acacheerror withhandled: false, since no answer carries it. For the next 10 seconds that key starts no other refresh, so an upstream that is down is not called on every request; after them the next stale read tries again. invalidate,expireandshouldInvalidateCachelift the pause at once.- Once an entry is past its stale window (
maxAge + staleMaxAge, ormaxAgewithoutswr) a request waits for a new value, and an error reaches it. staleIfError: nkeeps the entrynseconds longer: storage keeps it that much longer, and a request that waits on a fill that throws or times out gets the old entry instead of the error, with the cache statusSTALE. ItsCache-Controlgives it no fresh lifetime:s-maxage=0from a rule,max-age=0where amax-ageis sent, withstale-if-error=<n>kept.- During the 10-second pause such a request gets the old entry without waiting.
- A route rule adds
stale-if-error=<n>to theirCache-Control, so a CDN may do the same.
export const getPrices = defineCachedFunction(() => fetchPrices(), { maxAge: 60, staleMaxAge: 240, staleIfError: 3600 })
- The old entry is never served when it was removed (
invalidate,shouldInvalidateCache,invalidateRouteCache), when one of its tags was revalidated with the default"expire"mode, or when its key was written, removed or expired, or one of its tags revalidated, while the fill ran. - An entry
expire()marked is still served on error within the window. On a rule, set it incache(routeRules: { "/prices": { cache: { maxAge: 60, staleIfError: 3600 } } }) or inserver.cache.defaults; a value that is not a non-negative number is aTypeErrorin code and a config error for a rule:routeRules["/prices"].cache.staleIfError must be a non-negative number of seconds (got "1h").
import { defineCachedFunction } from "hamur/server"
export const getStars = defineCachedFunction(
async (repo: string) => {
const response = await fetch(`https://api.github.com/repos/${repo}`)
const data = (await response.json()) as { stargazers_count: number }
return data.stargazers_count
},
{ maxAge: 300, getKey: (repo) => repo },
)
- For a function the default key is the serialized arguments, so an argument that is an event, or anything the serializer cannot hold, needs a
getKey. - Entries are named after the function and a hash of its source, so two functions with the same source and different closures share entries unless
getKeytells them apart.
Route rules
- A route rule applies the same cache to pages.
swr: 600is amaxAgeof 600 seconds with stale-while-revalidate;cachetakes{ maxAge, swr, staleMaxAge, varies }. The same rule caches aGEThandler route at that path.cache: falseturns both off.- A redirect, a reload or an error answer is not stored.
swr: trueand acachewithoutmaxAgeboth mean 1 second.- The key holds the build id, the host, the path and the query, and the values of the
variesheaders, nothing else. - The cookie is not in it, and the page renders on a cache fork with an empty
event.context, so a page whose data depends on the user needsvaries: ["cookie"]and reads the session itself rather than a value server middleware set. - A request with an
authorizationheader is neither served from the rule cache nor stored in it, unlessvarieslistsauthorization. - A WebSocket upgrade is never cached.
invalidateRouteCache(url)fromhamur/serverremoves the page and aGEThandler route that the rules stored for an absolute URL.
import { defineConfig } from "hamur"
export default defineConfig({
framework: "react",
routeRules: {
"/blog/**": { swr: 600 },
"/pricing": { cache: { maxAge: 60, staleMaxAge: 3600 } },
},
})
Draft mode, noStore and cached functions
useDraftModeshows an editor unpublished content and skips every cache.noStorekeeps one answer out of the cache. A prerendered page that calls it fails with/dashboard called noStore() and cannot be prerendered.defineCachedFunctionhas the options that expire, bypass, check and shape an entry.
On-demand revalidation
A CMS or a deploy script that runs outside the app can revalidate its caches over HTTP. Turn the endpoint on in the config:
// hamur.config.ts
import { env } from "hamur"
export default {
server: { revalidate: { token: env("REVALIDATE_TOKEN") } },
}
- Without
token, the token is theHAMUR_REVALIDATE_TOKENenvironment variable. It must be at least 32 characters; a missing or shorter token stops the bun and node servers at start withserver.revalidate needs HAMUR_REVALIDATE_TOKEN or server.revalidate.tokenorserver.revalidate token must be at least 32 characters (got 12), and on the other presets every request answers 500. pathmoves the endpoint, belowapp.baseURLas always; it is/_hamur/revalidateby default.- The build fails when
pathis the exact path of a page or a server route, which the endpoint would hide.
curl -X POST https://example.com/_hamur/revalidate \
-H "Authorization: Bearer $HAMUR_REVALIDATE_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "tags": ["posts"], "paths": ["/blog/a", { "path": "/docs", "type": "layout" }] }'
- The body runs
revalidateTagfortagsandrevalidatePathfor each entry ofpaths, a path or{ path, type }, and the endpoint answers200with{ "revalidated": true, "now": <ms> }. - Every tag and path is checked before any is revalidated.
| Status | When |
|---|---|
401 | no Authorization: Bearer <token>, or another token: { "error": "Unauthorized" } with WWW-Authenticate: Bearer. The token is compared in constant time |
405 | another method than POST, with Allow: POST |
400 | a body that is not { tags?, paths? }, with the message Expected { tags?: string[], paths?: Array<string | { path: string, type?: "page" | "layout" }> }, more than 1000 tags and paths together (Expected at most 1000 tags and paths in one request (got 1002)), or a tag or path that revalidateTag or revalidatePath refuses, with its TypeError text |
413 | a body over server.maxBodySize |
500 | the tag index could not be written; the error is reported to the error hook as a cache error |
The endpoint answers before server middleware, reads no cookie and so skips the origin check, and its answers carry Cache-Control: no-store.
ETags and 304
- An answer a cache stores gets an
etagand alast-modifiedunless the handler set its own. - The
etagis weak,W/"<32 hex>", the first 16 bytes of SHA-256 of the body, because compression happens after the cache. last-modifiedis the time the entry was filled. This covers thecacheandswrroute rules (pages,/_hamur/dataand server routes), and thecacheof aGEThandler.- A
GETorHEADrequest whoseIf-None-Matchmatches, or, without it, whoseIf-Modified-Sinceis at or afterlast-modified(to the second), gets304with no body and the entry'setag,last-modified,cache-control,expires,varyandcontent-location. If-None-Matchcompares weakly, takes a comma-separated list and*.- A stale entry answers
304as well and starts its refresh. GETandHEADkeep their own entries.- An answer that is not stored gets no
etagfrom the cache: a draft request, aprivate,no-cacheorno-storeanswer, a cookie, aRangerequest. - The cache never answers
304for them.
Query and cookie allowlists
A cache keys on the whole query string by default (allowQuery: true), and no cookie reaches the cached render unless varies lists cookie. Two options narrow that, on a GET handler's cache and on the rule key cache:
routeRules: { "/blog/**": { cache: { maxAge: 60, allowQuery: ["page"], allowCookies: ["theme"] } } }
allowQuery: ["page"]keys on those names only, sorted by name, with each name's values in request order, and removes every other parameter from the URL the render sees.?page=2&utm=xand?utm=y&page=2share one entry, and the handler reads onlypage.allowQuery: []keys on the path alone.allowCookies: ["theme"]lets only those cookies reach the render and joins them to the key, so two visitors with the samethemeand different sessions share one entry and the handler never sees the session. The answer getsVary: Cookie, onGETandHEADalike.allowCookieswithvariesnamingcookieis refused:TypeError: allowCookies and varies: ["cookie"] cannot be set together; allowCookies already keys on the named cookies, and for a rule the config errorrouteRules["/x"].cache: allowCookies and varies: ["cookie"] cannot be set together. A rule's bad value isrouteRules["/x"].cache.allowQuery must be true or an array of query namesorrouteRules["/x"].cache.allowCookies must be an array of cookie names.allowCookieswith a rule that tests a cookie inwhenis the same conflict and is a config error.isrwithallowCookies(orvariesnamingcookie) is a build error on vercel and netlify, whose CDN keeps the page and ignoresVary: useswrorcache, or dropallowCookies.- A request with
authorizationstill bypasses the cache unlessvariesnames it. - On vercel an
isrrule'scache.allowQuerylist, sorted, is the prerender config'sallowQuerywith__isr_route.
Cache status
server.cache.statusHeadersends the cache status of an answer inx-hamur-cache:trueinhamur dev,falsein a build.- A string names the header (
statusHeader: "x-cache"). - The
statusHeaderoption of aGEThandler'scacheand the rule keycache.statusHeader, win over the config.
| Value | The answer |
|---|---|
HIT | came from a fresh entry |
STALE | came from a stale entry; one refresh started |
MISS | ran the handler for this request, also when the answer could not be stored |
REVALIDATED | is a 304 from the entry's validators |
BYPASS | a cache would have taken the request and skipped it: draft mode, authorization without varies naming it, a Range request, a request with a CSP nonce, shouldBypassCache returning true |
- A request that is not
GETorHEADand a WebSocket upgrade get no header. - The header is added to each answer and is never stored in an entry.
- The
cache <name>span of a traced request carries the same value ashamur.cache.status.
Your own validators
- A
GETorHEADanswer with status200that carries its ownetagorlast-modifiedgets304with no body when the request'sIf-None-MatchorIf-Modified-Sincematches, cached or not, and whateverserver.etagsays. - An answer that sets a cookie keeps its body.
server.etag: true(or"weak","strong") adds the validator itself to aGETorHEAD200answer a handler built from a string, bytes, a blob or a JSON value of at most 1 MiB. It isW/"<32 hex>"or, strong,"<32 hex>": the first 16 bytes of SHA-256 of the body, the hash a cache entry uses.- A stream, a page, a file, a
Responsethe handler built, and an answer with aset-cookie, ano-store, anetagof its own or a draft request get none. - A
HEADrequest carries no body to hash, so it gets one only from a cache. On the bun and node presets a strongETagof an answer thatserver.compresscompresses becomes"<32 hex>-<coding>", andIf-None-Matchwith that form matches.
handleCacheHeaders sets the validators from what the handler knows, before it does its work:
import { defineHandler, handleCacheHeaders } from "hamur/server"
export const report = defineHandler({
route: "/api/report",
method: "GET",
async handler(_, { event }) {
const meta = await reports.latestMeta()
if (
handleCacheHeaders(event, { etag: `"${meta.version}"`, modifiedTime: meta.updatedAt, cacheControls: ["private"] })
)
return null
return reports.render(meta)
},
})
See handleCacheHeaders.
CDN headers
- A route rule also tells a CDN how long it may keep the answer.
- A cached 2xx answer to a
GETorHEADthat sets no cookie and has nocache-controlof its own gets
Cache-Control: public, s-maxage=<maxAge>, stale-while-revalidate=<staleMaxAge, else 31536000>
stale-while-revalidateis left out whenswrisfalse.cache.variesis added toVary. On Netlify the same value is also sent asNetlify-CDN-Cache-Control.- A response that sets a cookie or its own
cache-control, an event stream and a206are left as they are. This is the rule cache only.
import { defineConfig } from "hamur"
export default defineConfig({
framework: "react",
routeRules: {
"/blog/**": { swr: 600 },
"/prices": { cache: { maxAge: 60, swr: false, varies: ["accept-language"] } },
"/account/**": { cache: false },
},
})
Here /blog/** answers public, s-maxage=600, stale-while-revalidate=31536000, and /prices answers public, s-maxage=60 with Vary: accept-language.
CDN tags and purge
- On Netlify and Vercel an answer that comes from a cache entry, and on Netlify an
isranswer that only its CDN keeps, also tells the CDN the entry's cache tags, comma-separated, inNetlify-Cache-TagorVercel-Cache-Tag. That covers thecacheandswrroute rules and thecacheof aGEThandler. - The explicit tags come first, then
path:,route:and thelayout:tags from the deepest:
Netlify-Cache-Tag: posts,path:/blog/a,route:blog-slug,layout:/blog/a,layout:/blog,layout:/
- An answer that comes from no cache, and one whose
Cache-Controlisprivateorno-store, carries no tag header. Each host takes a limited list: Vercel 128 tags, Netlify 500. - A longer list is cut from the end and the server warns once per route:
Cache tags of /blog/a pass the vercel limit of 128; the last 3 are not sent. On Netlify anisranswer carries itspath:,route:andlayout:tags and every tag its loads added withcacheTagor through cached functions. - On Vercel an
isranswer carries none, since Vercel reads no header of an ISR answer. On Cloudflare no answer carries a tag header: the Worker's answer is not kept in the edge cache, so the header would only reach the visitor. - With the host's credentials in
server.cdnPurge,revalidateTagandrevalidatePathalso purge those tags from the CDN, once the tag index is written. - The purge runs after the answer through
waitUntilof the request, or is awaited outside a request.
// hamur.config.ts
import { env } from "hamur"
export default {
server: {
cdnPurge: {
vercel: { projectId: "your-project-id", token: env("VERCEL_PURGE_TOKEN") },
},
},
}
| Preset | Credentials | Call |
|---|---|---|
cloudflare | cdnPurge.cloudflare: { zoneId, token }, a token with the Cache Purge permission | POST https://api.cloudflare.com/client/v4/zones/<zoneId>/purge_cache with { "tags": [...] }, 30 tags per call. It reaches what the zone's cache holds under those tags, such as an origin behind the zone; Hamur's own answers carry no tags there |
netlify | cdnPurge.netlify: { siteId?, token? }; without them the function's own SITE_ID and NETLIFY_PURGE_API_TOKEN, which Netlify sets | POST https://api.netlify.com/api/v1/purge with { "site_id", "cache_tags": [...] }, one call |
vercel | cdnPurge.vercel: { projectId, teamId?, token } | POST https://api.vercel.com/v1/edge-cache/dangerously-delete-by-tags for revalidateTag's default mode "expire", …/invalidate-by-tags for "stale", with ?projectIdOrName=<projectId>&teamId=<teamId> and { "tags": [...] }, 16 tags per call |
revalidatePath("/blog/a")purgespath:/blog/a,revalidatePath("/blog/[slug]", "page")the page'sroute:tag andrevalidatePath("/blog", "layout")layout:/blog.- A
tokenis a string orenv("NAME"), read at server start; keep it in the environment, not in the config file. - A string token is written into the server output, and the build warns:
server.cdnPurge.netlify.token is a literal string, which the build writes into the server output; use env("NAME") to read it at server start. - Only the preset's own credentials go into the server bundle, never into the client or
hamur.json, and credentials for another host make the build warn:server.cdnPurge.netlify is read by the netlify preset only. - Without credentials nothing is sent.
- A purge call that fails, answers other than 2xx or is rate limited is logged as a
cacheerror with the host's status and answer, never the token; it is not retried and the revalidation still succeeds, so the CDN keeps its copy until itss-maxageruns out.