Skip to content

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 as fs({ base: ".data/cache" }), whose options are typed, and a mount that the config does not name is kept in memory, except data.
  • A mount written as { driver: "redis" } fails at load: storage.cache: { driver: "redis" } was removed; write redis({ … }) from "hamur/storage".
  • data is a file store by default: without a data mount, useStorage("data") keeps its items in .data/kv under hamur dev and on the bun, node and static presets (hamur init lists .data/ in .gitignore). On other presets it is in memory and logs once per process storage "data" is in memory on vercel; configure storage.data.
  • Keys are separated by :; / and \ separate them too, so user/1 is the same key as user:1.
  • A prefix matches whole segments: getKeys("user") returns user, user:1 and user:2:x, not users:1.
  • A segment that is ., .. or contains a NUL byte throws.

Metadata, counters and batches

  • getMeta(key) gives what the backend knows (mtime and size on memory, fs, sqlite, s3 and db; expires, in ms, where an expiry is stored) merged with the fields setMeta(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. setMeta of a missing item throws TypeError: 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, and ttl applies only when this call creates the key, which makes a fixed window for a rate limit. It is atomic on memory, sqlite, redis, db and planetscale; on every other driver it runs under a lock of this process and logs once per mount increment on <driver> is not atomic across instances. Values and results must be safe integers.
  • getItems(keys) gives { key, value } in the given order, value undefined for a missing key, and setItems([{ key, value, options }]) writes many (a value of undefined removes the key). They are one MGET on redis, one query on sqlite, db and planetscale, and the single calls together elsewhere; a refused key throws before anything is written. getKeys(prefix, { maxDepth }) counts segments below the prefix: a:1 and a:b:2 under a with maxDepth: 1 give a:1.
ts
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) calls callback("update" | "remove", key) after every change made through this process (setItem, setItems, increment, setMeta, removeItem, clear once per key) and gives the function that stops it.
  • The fs driver also reports files that another process changed, with a recursive fs.watch debounced for 50 ms, and does not report its own writes twice.
  • A callback that throws is logged at error and does not stop the others.
ts
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 and restoreSnapshot(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.
ts
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 full Storage whose keys are relative to users:: 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, getItems and setItems are then typed by key, a literal key that matches no pattern fails tsc, and prefixStorage keeps the schema.
ts
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

  • devStorage replaces the storage mount of the same name, options and all, under hamur dev and in the prerender of every preset.
  • A $development.storage block applies first, then devStorage on top; devStorage is the key that also covers the prerender, where a platform driver such as cloudflare-kv cannot run.
  • A mount replaced this way imports no driver and opens no connection.
  • The build checks storage drivers against the preset, not devStorage drivers, and a Cloudflare bundle carries no devStorage driver.

Mounting at run time and custom drivers

  • mountStorage(name, driver) replaces a mount of the same name, and unmountStorage(name) removes one and waits for its driver's dispose(); after it, useStorage(name) is the default mount for that name: a fresh memory mount, or for data the .data/kv file store on bun, node and static.
  • Calls already running finish first, a Storage you kept refuses new calls (storage "x" was unmounted; call useStorage("x") for the current mount), and the drain disposes every driver once.
ts
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) and clear(prefix), and optionally getItems, setItems, getMeta, increment, watch and dispose.
  • A driver that leaves the optional ones out gets the fallbacks.
  • A prefix ending in : matches only keys that start with it.
  • implementStorageDriver of hamur/server types a factory and gives it back as it is:
ts
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 defineStorageDriver of hamur/storage: it takes driver, a path relative to the config file (./server/drivers/mine.ts) or a package whose default export is a factory (options, mount) => StorageDriver, and presets, 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

FunctionRuns onOptions
memory()every presetmax, 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, staticbase (required), the directory; readOnly, noClear, ignore (see below)
sqlite()bun, staticpath (required), table
redis()bun, node, cloudflare, staticurl, base (a key prefix)
s3()every presetbucket, region, endpoint, accessKeyId, secretAccessKey, sessionToken, virtualHostedStyle, base
cloudflareKV()cloudflarebinding (required), base
cloudflareR2()cloudflarebinding (required), base (a key prefix)
cloudflareCache()cloudflarename (for caches.open; default caches.default)
netlifyBlobs()netlifyname (required), deployScoped
vercelBlob()vercelbase (a key prefix)
azureBlob()every presetaccountName, containerName (required), accountKey or sasToken, base, endpoint
planetscale()every preseturl (required, with credentials), table
vercelRuntimeCache()vercelnone
overlay()every presetlayers, a list of mount configs, topmost first (see below)
nullDriver()every presetnone
github()every presetrepo (required, owner/name), branch (default main), dir, token, ttl (seconds the file list is cached, default 600); read-only
http()every presetbase (required), the absolute URL of a createStorageHandler route; headers, sent with every request
dbStorage() of @hamur/db/storageevery preset the connection's connector runs onconnection (default default), table (default hamur_storage); needs the @hamur/db module, see Database
defineStorageDriverits presetsthe factory's own, see above
  • static runs the server on Bun while it builds, to prerender, so it takes what bun takes.
  • A mount whose driver the preset cannot run is a build error that names the mount. On vercel and netlify the memory driver is per function instance; s3, netlify-blobs (on Netlify), vercel-blob and vercel-runtime-cache (on Vercel) are shared.

fs

  • fs takes three more options.
  • With readOnly: true, a write, a removal or clear throws TypeError: storage "<mount>" is read-only; reads work.
  • With noClear: true, clear does nothing.
  • ignore is a list of glob patterns, matched against the key with : read as /, so ["tmp/**", "**/*.bak"] leaves tmp:a and b:c.bak out of getKeys; getItem and hasItem still 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 overlay driver stacks mounts.
  • layers is 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.
  • removeItem writes 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; clear does the same for every key it holds under the prefix. This puts a writable layer over files you ship:
ts
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 github driver 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 path a/b/c.json is the key a:b:c.json. It lists the files with one call to the GitHub API and keeps the list for ttl seconds, so a new commit shows after that long; a file is fetched when you read it.
  • Without a token GitHub allows 60 requests an hour per IP address, and a private repository is not found.
  • Files are read as server assets are: getItem parses a .json file, gives other text files (.md, .txt, .yaml, …) as a string and any other file as bytes, and getItemRaw gives the bytes of any file.
  • A read gets the file of the commit the list came from, even if the branch has moved since.
  • dir makes 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.
  • getMeta has the size and no mtime.
  • Every write, removeItem and clear throws TypeError: 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 with github rate limit exceeded and the time to try again.

redis, s3 and cloudflare-kv

  • The redis driver uses url (redis:// or rediss:// for TLS), else VALKEY_URL or REDIS_URL, else localhost:6379. On bun it uses Bun.redis; on node and cloudflare it uses a client of Hamur's own over node:net/node:tls and cloudflare: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.env on node and from the Worker's env on cloudflare.
  • The s3 driver reads what you leave out from the S3_* and AWS_* variables. It runs on every preset: Bun's client on bun, and a SigV4 signer of Hamur's over fetch everywhere 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/blob for files, and presigned URLs, which a storage value cannot be. For cloudflare-kv, binding is the name of a kv_namespaces entry in the Worker configuration.
  • Put that entry in a wrangler.json or wrangler.jsonc in 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:

jsonc
{
  "name": "my-app",
  "kv_namespaces": [{ "binding": "CACHE", "id": "<namespace id>" }],
  "vars": { "ENVIRONMENT": "production" },
}

netlify-blobs

  • The netlify-blobs driver talks to the Netlify Blobs HTTP API with the site's NETLIFY_BLOBS_CONTEXT, which Netlify sets for functions; without it the first use fails with netlify-blobs needs NETLIFY_BLOBS_CONTEXT (runs on Netlify).
  • name is the store's name (at most 64 bytes, no /); with deployScoped the 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, and increment is not atomic across function instances.

cloudflare-r2 and cloudflare-cache

  • For cloudflare-r2, binding is the name of an r2_buckets entry 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-cache driver 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 on workers.dev. It can evict an item before its ttl.
  • It cannot list keys: getKeys and clear throw TypeError: cloudflare-cache cannot list keys. Use it for caches, not for data you need back.

planetscale

  • The planetscale driver talks to PlanetScale's HTTP SQL API with fetch, so it runs wherever your server does.
  • url is https://<username>:<password>@<host> or the mysql://<username>:<password>@<host> string PlanetScale shows for a password (http:// is accepted only for localhost); keep it in an environment variable, not in the config file.
  • Items live in one table, hamur_storage unless table says otherwise, created at first use: give each planetscale mount 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.
  • increment is 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-blob reads BLOB_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 no access option: a public blob is served from a CDN cache that cannot be bypassed, so a mount could read an old value.
  • Use @hamur/blob for public files.
  • vercel-runtime-cache keeps items in the Vercel Runtime Cache of the function's region.
  • Vercel can evict an item before its ttl, and it cannot list keys: getKeys and clear throw TypeError: vercel-runtime-cache cannot list keys.
  • Outside a Vercel Function it throws vercel-runtime-cache runs only on Vercel Functions.
  • Mounts on vercel-runtime-cache share one cache, so give a key a prefix of its own when two mounts use it.

http

  • The http driver reads and writes a mount of another app over HTTP. That app serves the mount with createStorageHandler(mount, { authorize }) from hamur/server in a raw handler on a catch-all route, and authorize decides who may read and who may write: throw to refuse, a createError({ status: 403 }) to answer that status, anything else answers 401, and returning false answers 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) the fs driver keeps SECRET and secret in one file, so with an fs mount there, write authorize rules that do not depend on case, such as comparing key.toLowerCase().
  • The driver sends headers with every request, so a token goes there.
  • Values travel as the stored bytes with their expiry in x-hamur-expires, so a ttl set 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.
  • increment is not atomic across instances on this driver.
  • The protocol is in the API reference.
ts
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),
})
ts
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-blob keeps one block blob per item at <base><key> in a container that already exists, over the Blob REST API with fetch, so it runs on every preset. Give accountName, containerName and either accountKey (the base64 key, signed with Shared Key by crypto.subtle) or sasToken; AZURE_STORAGE_ACCOUNT, AZURE_STORAGE_KEY and AZURE_STORAGE_SAS_TOKEN fill what the config leaves out.
  • endpoint points 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 implementStorageDriver and mount it with defineStorageDriver of hamur/storage (see the server API reference, mountStorage, unmountStorage, implementStorageDriver).

Expired items

  • An expired item reads as missing.
  • The fs, s3, cloudflare-r2, vercel-blob and azure-blob drivers do not delete it when it is read, so it stays until you write the key again, call removeItem or clear, or (on S3 and R2) a lifecycle rule on the bucket removes it.
  • cloudflare-kv asks KV to expire every item with a ttl, 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_PASSWORD in app/env.ts and set it where the server runs; a name app/env.ts does not declare fails at load with storage.cache.password reads env "REDIS_PASSWORD", which app/env.ts does not declare, and the old form { runtimeConfig: "redisPassword" } with storage.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:

ts
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 ?? "") with STORAGE_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.
  • encrypt goes on the mount, not on an overlay layer (that is a config error), and a driver that reads files, such as github, cannot be encrypted.
  • increment on an encrypted mount reads, adds and writes the value again, so it is not atomic across instances on any driver.
  • createStorageHandler serves an encrypted mount's stored bytes, that is the ciphertext.
  • What encrypt does not protect: keys, expiry times, setMeta fields, 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 mount useStorage("assets:server"); a module adds assets:<name> with addServerAssets.
  • A path becomes a key with / turned into :, so server/assets/data/a.json is data:a.json.
  • getItem parses a .json file, gives other text files as a string and anything else as bytes, getItemRaw gives the bytes, and getMeta gives size and mtime.
  • A write throws TypeError: assets:server is read-only, and a storage mount named assets:… fails at load.
  • On bun, node, vercel and netlify a file up to 1 MB is inlined in the bundle and a larger one is copied next to it. On cloudflare every 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) from hamur/server reads an imported asset URL as a Response.

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.

ts
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(),
  },
})
ts
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)
  },
})
NuxtHubHamur
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 handlersdefineCachedFunction, 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-kv needs a kv_namespaces entry for each binding in your wrangler.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:

ts
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(),
  }
})
ts
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 mongodb package is your app's dependency, not Hamur's.
  • defineStorageDriver lists bun and node, the presets that can open the connection, so a build for another preset fails; devStorage swaps it for fs while you develop.
  • dispose closes the client when the mount is replaced or the server drains.
  • Without increment the 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:

ts
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 ttl with a TypeError. 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 missing customId. For user uploads, @hamur/blob with 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 base names another; each kind uses cache until you mount its own (Where entries live).
  • cache on a GET handler 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 cache or swr on a route's path caches whatever that route answers, a Response included: a feed, an image, a raw route. The cache of a handler stores only a value it returns, and refuses raw.
ts
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:

ts
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" } })
  },
})
ts
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "react",
  routeRules: {
    "/feed.xml": { cache: { maxAge: 600, staleMaxAge: 3600, streamFill: true } },
  },
})
OptionMeaning
maxAgeseconds an entry is fresh; required, and positive: 0 throws a TypeError
swrserve a stale entry at once and refresh it in the background; default true, and false for the cache of a handler
staleMaxAgeseconds past maxAge a stale entry may still be served; without it, no limit
getKeythe cache key; see below. The cache of a handler gets (input, event) and can only widen its own entries; a rule takes none
variesrequest header names whose values are part of the key (a handler's cache and rules only)
maxResolveTimeseconds a fill may run; default 30; see Fill deadline
staleIfErrorseconds an entry past its stale window is still served when the fill that replaces it fails; see Serving stale on error
basethe storage mount, the kind's mount by default (Where entries live), or a list of mounts, fastest first; see Tiers and versions
integritya 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, deserializecached functions only; see Checking and shaping entries
maxEntrySizebytes: route rules only; a larger answer is not stored; see Entry size
streamFilltrue: 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 varies headers: a.test/x?q=1 and b.test/x?q=1 are two entries.
  • Only GET and HEAD are cached.
  • The handler runs on a cache fork, a copy of the request that carries only the varies headers and no client address.
  • A handler that reads the cookie or authorization, as a session does, gets nothing unless those names are in varies; without them it always runs as an anonymous visitor. Its event.context starts empty, so what server middleware put there for the visitor (a context.user read 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-control has no no-store, no-cache or private.
  • 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, every varies variant included, and invalidate(...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:

ReaderMemoized callsKey
the request-bound fetch: a load's ctx.fetch, useRequestFetch(), useApp().fetch on the serverGET 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 callthe handler and its serialized input
memo(fn)every call of the returned functionthe wrapper and its serialized arguments
  • A parent and a child load that both call getUser() run it once.
  • A call that arrives while the same one runs joins it.
  • A fetch caller gets its own Response of the one buffered answer, so responseType and $fetch.raw work per call; a handler or memo caller 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 not GET or HEAD, clears the memo before it runs and again once it settles, and refresh(event, fn, input) clears it too, so a read after a mutation in the same request sees the mutation, even when a parallel load read 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) calls fn every time, and the global $fetch is not request-bound, so it memoizes nothing.
ts
// server/users.ts
import { memo } from "hamur/server"

export const findUser = memo((id: number) => db.users.find(id))

Fetch cache

  • On the server, serverCache keeps the answer of a $fetch GET or HEAD call in the cache:functions mount (cache when it is not mounted), so later calls, from any request, skip the upstream until the entry is stale. It takes maxAge, swr, staleMaxAge, profile, tags, maxResolveTime, staleIfError and varies, resolved as every cache's: server.cache.defaults, then the profile, then the fields.
  • Without a maxAge from one of them the call throws TypeError: $fetch serverCache needs maxAge, a profile or server.cache.defaults.maxAge.
  • The option is called serverCache because cache is fetch's own field. In the browser it is ignored, so a file shared with the client compiles and runs.
ts
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 serverCache call is anonymous: the request-bound fetch (ctx.fetch, useRequestFetch(), useApp().fetch) forwards no cookie or authorization of the visitor, and a set-cookie in its answer does not reach the page.
  • Headers the call sets are sent as they are and join the key only when varies names them.
  • A cookie or authorization header the call sets must be named in varies, so each value has its own entry; otherwise the call throws a TypeError.
  • A fetch:request hook 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 a serverCache call makes the call throw a TypeError.
  • The key is the method, the final URL (after baseURL and query; an in-process URL on the request's origin, so each host has its own entries) and the values of the varies headers, stored as fetch:<sha256>.
  • A body larger than the entry cap (server.cache.defaults.maxEntrySize, else half the maxBytes of a memory mount 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 revalidateTag of them reaches it.
  • Only a 2xx answer other than 206, without set-cookie and without no-store, no-cache or private in its cache-control, is stored; any other answer reaches its caller, a FetchError included, and the next call runs again. Each caller gets its own Response of the stored bytes, so responseType applies after the cache.
  • revalidateTag reaches the entry through its tags, and an in-process URL also carries the implicit path: tag, so revalidatePath("/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's serverCache: false turns it off. Another method ignores serverCache.

Entry size

  • maxEntrySize (bytes, a positive integer) caps one stored answer. It defaults to half the maxBytes of the memory mount that holds the entries (50 MB of the default cache mount's 100 MB), and there is no cap on another driver.
  • An answer whose content-length is 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.maxEntrySize and server.cache.defaults.maxEntrySize; it is not server.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.
ts
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 maxEntrySize stops 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 etag or last-modified the 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 GET answer whose body is a stream; a string, bytes or JSON value is already whole and is stored as before, and a HEAD fill 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:

MountHolds
cache:pagesthe cache, swr and isr route rules of pages, server-only components and server islands
cache:handlersthe route rules of server routes
cache:functionsdefineCachedFunction, the cache of a GET handler and $fetch serverCache
cache:tagsthe tag index that revalidateTag and revalidatePath write
ts
// 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 mountStorage names; a mount made at run time takes over from cache with 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 base option, or a rule's cache.base, wins over the kind.
  • invalidate, expire, resolveKeys, invalidateRouteCache and the fills act on the kind's mount, and revalidateTag on cache:tags, which reaches entries on every mount.
  • Entries a kind wrote to cache stay there when you add its mount later, and are no longer read; clear them with useStorage("cache").clear("handlers") (or functions, fetch) if the driver keeps them.
  • A backend that is not a key-value store is a storage driver (custom drivers): its getItem, setItem with an expiry and removeItem are all a cache needs, and revalidateTag writes only the tag index.
  • A driver whose getKeys or clear throws, as cloudflare-cache's and vercel-runtime-cache's do, still serves entries and tag revalidation, while invalidate and expire of a handler, which list the keys below its URL, throw that error.

Tiers and versions

  • base names 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.base for a rule.
ts
// 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"] } } },
})
ts
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, deserialize and validate pass). When that is not the first mount, the entry is written back to the mounts before it through event.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, shouldInvalidateCache and invalidateRouteCache act 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 revalidateTag and revalidatePath reach the entry in each of them.
  • A mount that fails to read is a cache error and the next mount is read; one that fails to write is a cache error and the others are still written. invalidate and expire act on every mount even when one fails, then throw the first failure.
  • Without maxEntrySize, the cap is half the maxBytes of the smallest memory mount in the list.
  • The isr seed 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 an invalidate.
  • A base that is not a mount name or a non-empty list of distinct names is TypeError: 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.
  • integrity replaces 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 an integrity: two getPost functions with integrity: "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 Range header never reads or writes the cache, in the cache of a handler and in the cache and swr route 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-9 with the whole body, and a stored 206 would be sent as the whole resource to later visitors.
  • A page answer to a Range request also gets no CDN Cache-Control.

Fill deadline

  • Callers that miss on the same key share one fill.
  • maxResolveTime is the number of seconds that fill may run, 30 by default.
  • If the handler has not finished by then, every caller waiting for it gets a HamurError with status 504 and the message Cache 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.signal to fetch stops at the deadline.
  • defineCachedFunction has no request and only stops waiting.
ts
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>
  },
})
  • 0 or Infinity waits without a limit. Any other value that is not a non-negative number is a TypeError for a handler's cache and a config error for a route rule. On a route rule, set it in cache (Configuration); a rule written as swr: 600 uses the default.
  • A 504 in a background swr refresh 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 the error hook as a cache error with handled: 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, expire and shouldInvalidateCache lift the pause at once.
  • Once an entry is past its stale window (maxAge + staleMaxAge, or maxAge without swr) a request waits for a new value, and an error reaches it.
  • staleIfError: n keeps the entry n seconds 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 status STALE. Its Cache-Control gives it no fresh lifetime: s-maxage=0 from a rule, max-age=0 where a max-age is sent, with stale-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 their Cache-Control, so a CDN may do the same.
ts
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 in cache (routeRules: { "/prices": { cache: { maxAge: 60, staleIfError: 3600 } } }) or in server.cache.defaults; a value that is not a non-negative number is a TypeError in code and a config error for a rule: routeRules["/prices"].cache.staleIfError must be a non-negative number of seconds (got "1h").
ts
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 getKey tells them apart.

Route rules

  • A route rule applies the same cache to pages.
  • swr: 600 is a maxAge of 600 seconds with stale-while-revalidate; cache takes { maxAge, swr, staleMaxAge, varies }. The same rule caches a GET handler route at that path.
  • cache: false turns both off.
  • A redirect, a reload or an error answer is not stored.
  • swr: true and a cache without maxAge both mean 1 second.
  • The key holds the build id, the host, the path and the query, and the values of the varies headers, 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 needs varies: ["cookie"] and reads the session itself rather than a value server middleware set.
  • A request with an authorization header is neither served from the rule cache nor stored in it, unless varies lists authorization.
  • A WebSocket upgrade is never cached.
  • invalidateRouteCache(url) from hamur/server removes the page and a GET handler route that the rules stored for an absolute URL.
ts
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

  • useDraftMode shows an editor unpublished content and skips every cache.
  • noStore keeps one answer out of the cache. A prerendered page that calls it fails with /dashboard called noStore() and cannot be prerendered.
  • defineCachedFunction has 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:

ts
// hamur.config.ts
import { env } from "hamur"

export default {
  server: { revalidate: { token: env("REVALIDATE_TOKEN") } },
}
  • Without token, the token is the HAMUR_REVALIDATE_TOKEN environment variable. It must be at least 32 characters; a missing or shorter token stops the bun and node servers at start with server.revalidate needs HAMUR_REVALIDATE_TOKEN or server.revalidate.token or server.revalidate token must be at least 32 characters (got 12), and on the other presets every request answers 500.
  • path moves the endpoint, below app.baseURL as always; it is /_hamur/revalidate by default.
  • The build fails when path is the exact path of a page or a server route, which the endpoint would hide.
sh
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 revalidateTag for tags and revalidatePath for each entry of paths, a path or { path, type }, and the endpoint answers 200 with { "revalidated": true, "now": <ms> }.
  • Every tag and path is checked before any is revalidated.
StatusWhen
401no Authorization: Bearer <token>, or another token: { "error": "Unauthorized" } with WWW-Authenticate: Bearer. The token is compared in constant time
405another method than POST, with Allow: POST
400a 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
413a body over server.maxBodySize
500the 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 etag and a last-modified unless the handler set its own.
  • The etag is weak, W/"<32 hex>", the first 16 bytes of SHA-256 of the body, because compression happens after the cache.
  • last-modified is the time the entry was filled. This covers the cache and swr route rules (pages, /_hamur/data and server routes), and the cache of a GET handler.
  • A GET or HEAD request whose If-None-Match matches, or, without it, whose If-Modified-Since is at or after last-modified (to the second), gets 304 with no body and the entry's etag, last-modified, cache-control, expires, vary and content-location.
  • If-None-Match compares weakly, takes a comma-separated list and *.
  • A stale entry answers 304 as well and starts its refresh.
  • GET and HEAD keep their own entries.
  • An answer that is not stored gets no etag from the cache: a draft request, a private, no-cache or no-store answer, a cookie, a Range request.
  • The cache never answers 304 for them.

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:

ts
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=x and ?utm=y&page=2 share one entry, and the handler reads only page. 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 same theme and different sessions share one entry and the handler never sees the session. The answer gets Vary: Cookie, on GET and HEAD alike.
  • allowCookies with varies naming cookie is refused: TypeError: allowCookies and varies: ["cookie"] cannot be set together; allowCookies already keys on the named cookies, and for a rule the config error routeRules["/x"].cache: allowCookies and varies: ["cookie"] cannot be set together. A rule's bad value is routeRules["/x"].cache.allowQuery must be true or an array of query names or routeRules["/x"].cache.allowCookies must be an array of cookie names.
  • allowCookies with a rule that tests a cookie in when is the same conflict and is a config error. isr with allowCookies (or varies naming cookie) is a build error on vercel and netlify, whose CDN keeps the page and ignores Vary: use swr or cache, or drop allowCookies.
  • A request with authorization still bypasses the cache unless varies names it.
  • On vercel an isr rule's cache.allowQuery list, sorted, is the prerender config's allowQuery with __isr_route.

Cache status

  • server.cache.statusHeader sends the cache status of an answer in x-hamur-cache: true in hamur dev, false in a build.
  • A string names the header (statusHeader: "x-cache").
  • The statusHeader option of a GET handler's cache and the rule key cache.statusHeader, win over the config.
ValueThe answer
HITcame from a fresh entry
STALEcame from a stale entry; one refresh started
MISSran the handler for this request, also when the answer could not be stored
REVALIDATEDis a 304 from the entry's validators
BYPASSa 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 GET or HEAD and 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 as hamur.cache.status.

Your own validators

  • A GET or HEAD answer with status 200 that carries its own etag or last-modified gets 304 with no body when the request's If-None-Match or If-Modified-Since matches, cached or not, and whatever server.etag says.
  • An answer that sets a cookie keeps its body.
  • server.etag: true (or "weak", "strong") adds the validator itself to a GET or HEAD 200 answer a handler built from a string, bytes, a blob or a JSON value of at most 1 MiB. It is W/"<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 Response the handler built, and an answer with a set-cookie, a no-store, an etag of its own or a draft request get none.
  • A HEAD request carries no body to hash, so it gets one only from a cache. On the bun and node presets a strong ETag of an answer that server.compress compresses becomes "<32 hex>-<coding>", and If-None-Match with that form matches.

handleCacheHeaders sets the validators from what the handler knows, before it does its work:

ts
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 GET or HEAD that sets no cookie and has no cache-control of its own gets
text
Cache-Control: public, s-maxage=<maxAge>, stale-while-revalidate=<staleMaxAge, else 31536000>
  • stale-while-revalidate is left out when swr is false.
  • cache.varies is added to Vary. On Netlify the same value is also sent as Netlify-CDN-Cache-Control.
  • A response that sets a cookie or its own cache-control, an event stream and a 206 are left as they are. This is the rule cache only.
ts
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 isr answer that only its CDN keeps, also tells the CDN the entry's cache tags, comma-separated, in Netlify-Cache-Tag or Vercel-Cache-Tag. That covers the cache and swr route rules and the cache of a GET handler.
  • The explicit tags come first, then path:, route: and the layout: tags from the deepest:
text
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-Control is private or no-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 an isr answer carries its path:, route: and layout: tags and every tag its loads added with cacheTag or through cached functions.
  • On Vercel an isr answer 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, revalidateTag and revalidatePath also purge those tags from the CDN, once the tag index is written.
  • The purge runs after the answer through waitUntil of the request, or is awaited outside a request.
ts
// hamur.config.ts
import { env } from "hamur"

export default {
  server: {
    cdnPurge: {
      vercel: { projectId: "your-project-id", token: env("VERCEL_PURGE_TOKEN") },
    },
  },
}
PresetCredentialsCall
cloudflarecdnPurge.cloudflare: { zoneId, token }, a token with the Cache Purge permissionPOST 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
netlifycdnPurge.netlify: { siteId?, token? }; without them the function's own SITE_ID and NETLIFY_PURGE_API_TOKEN, which Netlify setsPOST https://api.netlify.com/api/v1/purge with { "site_id", "cache_tags": [...] }, one call
vercelcdnPurge.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") purges path:/blog/a, revalidatePath("/blog/[slug]", "page") the page's route: tag and revalidatePath("/blog", "layout") layout:/blog.
  • A token is a string or env("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 cache error 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 its s-maxage runs out.