Postgres cache for Next.js and Astro
Keep Next.js cacheHandlers entries and Astro route cache responses in Supabase Postgres, so every instance shares them and a tag you expire takes effect everywhere.
better-supabase/cache-postgres stores cached pages and their tags in two
Postgres tables. A Next.js app on several instances then serves one set of
'use cache' entries, and updateTag or revalidateTag on one instance
expires the tag for all. Astro's route cache gets the same store as a cache
provider. Both use the bsb: tags that Caching
describes, and a write from outside the process reaches them through the
cache route.
Create the tables
postgresCacheSql() returns the SQL. Put it in a migration of your app. Both
tables enable row level security with no policy and revoke anon and
authenticated, so only the service role reads or writes them.
import { postgresCacheSql } from "better-supabase/cache-postgres";
console.log(postgresCacheSql({ prune: true }));prune: true schedules a pg_cron job that deletes entries past their hard
limit each hour. Without it, call store.prune() from a job of your own.
The SQL also creates two functions, bsb_cache_get and bsb_cache_mark_tags,
and grants them and the tables to service_role only. bsb_cache_get reads an
entry and checks its tags and the soft tags in one call. bsb_cache_mark_tags
writes each tag column with greatest(), so two instances that expire the same
tag at once keep the later expiry and never drop one.
The SQL is safe to run again. After an upgrade, add it to a new migration
instead of editing the one you pushed. Until the functions exist, the store
reads and writes the tables in two requests, reports this once through
onError, and tries the functions again after a minute.
| Option | Default | What it sets |
|---|---|---|
schema | public | the schema of the tables and functions |
entriesTable | bsb_cache_entries | the table of entries |
tagsTable | bsb_cache_tags | the table of tag states |
functionPrefix | bsb_cache | the names <prefix>_get and <prefix>_mark_tags |
prune | false | the hourly pg_cron job |
Pass the same options to the store, the handler and the Astro provider.
Next.js
Next.js loads a handler from a file, so the file creates the client and exports the handler as its default.
import { createClient } from "@supabase/supabase-js";
import { postgresCacheHandler } from "better-supabase/cache-postgres";
export default postgresCacheHandler({
client: createClient(url, serviceRoleKey, {
auth: { persistSession: false },
}),
});Set it in next.config.ts as cacheHandlers.remote (or remoteCacheHandler
in createNextConfig). The handler checks the entry's tags and the request's
soft tags on every read, treats a stale tag as revalidate: -1 so the entry is
served once more while Next.js renders a fresh one, and skips production
entries with expire: 0. Tags are read in chunks of 128, the size
applyCacheTags writes them in.
A miss takes a lease on the key, so one instance renders the entry. Another
instance that misses the same key waits up to wait milliseconds (250 by
default) for that entry, then renders itself; the lease runs out after
leaseMs (10 000 by default) when a render never stores its entry. The
bsb_cache_lease function hands the lease to exactly one caller, and
postgresCacheSql() creates it with the bsb_cache_leases table. On Vercel,
the remote handler Next.js ships can't be changed, so there only the entries of
bsb.kept() are coordinated across instances.
A database error on a read is a miss, and one on a write skips the write; pass
onError to log it. A failed updateTag throws, because a lost invalidation
would keep serving stale data.
Connect to Postgres directly
A Node.js server can skip PostgREST. Pass transport.postgres, an object with
a queryRaw(sql, params) method that returns the rows, instead of client.
Connect it as a role that owns the tables or has the service_role grants,
with a connection string that stays on the server. On the local stack a hit
takes about 0.2 to 0.6 ms this way, against 1.8 to 2.8 ms through PostgREST.
import { Pool } from "pg";
import { postgresCacheHandler } from "better-supabase/cache-postgres";
const pool = new Pool({ connectionString: process.env.CACHE_DATABASE_URL });
export default postgresCacheHandler({
transport: {
postgres: {
queryRaw: async (text, params) => (await pool.query(text, params)).rows,
},
},
});Delete one entry
postgresCacheStore(options).delete(key) removes one entry by its key, and
deletePath(path) removes the entries of a path. Use them when you know the
entry, and a tag when you know what changed.
Kept reads
postgresKeptStore() stores the entries of
bsb.kept()
in the same tables, under keys that start with kept:. It takes the same
client, transport and table options as postgresCacheStore().
import "server-only";
import { postgresKeptStore } from "better-supabase/cache-postgres";
export const bsb = createNext(betterSupabase, {
kept: { store: postgresKeptStore({ client: cacheClient }) },
});postgresKeptLease() takes the same options and returns only the fill lease,
for a store whose own lease is weaker: pass it as the lease option of
vercelRuntimeCacheAdapter to keep the entries in the Runtime Cache while one
instance fills a missing key. See
Keep reads across requests and deploys.
Astro
Astro loads a cache provider from a module whose default export is the
factory, so point entrypoint at the subpath. The provider reads the project
URL and the service role key from SUPABASE_URL and
SUPABASE_SERVICE_ROLE_KEY; urlEnv and keyEnv rename them.
import { defineConfig } from "astro/config";
export default defineConfig({
cache: {
provider: {
entrypoint: "better-supabase/cache-postgres/astro",
config: { urlEnv: "SUPABASE_URL" },
},
},
routeRules: {
"/products/[...path]": { maxAge: 60, swr: 300, tags: ["bsb:products"] },
},
});The provider stores a GET response whose CDN-Cache-Control has max-age,
with the tags of its Cache-Tag header, and never stores one with Set-Cookie
or Vary: Cookie. invalidate({ tags }) and invalidate({ path }) expire the
entries on every instance. Expire a table's pages from a write with the cache
route:
import { cacheRoute } from "better-supabase/server";
import cache from "better-supabase/cache-postgres/astro";
const provider = cache();
export const POST = cacheRoute({
betterSupabase,
caches: [
{
name: "astro",
invalidate: (target) =>
provider.invalidate({ tags: [`bsb:${target.table}`] }),
},
],
bearer: import.meta.env.CACHE_BEARER,
});Last updated on