Similar to what next-13 does with its overload of globalThis.fetch, this hooks make available an ISR fetcher under your app.locals.
Rather than performing a page caching, it implements an ISR mechanism at the request level.
This library assumes that your are using the cloudflare page / worker adapter.
I don't really know if we can call it an isr library stricto sensu because we need a way to populate / refresh the cache at build time. But I think it's pretty close to the experience we had with next.js and it's still pretty fast.
It first look up in the cache of the data center of the request. If a match is found it will return it. If no match is found and you have a KV namespace configured it will look up in the KV store and return the eventual result. If no KV match, it will fetch the request and return the response.
If any of the following condition are truthy it will revalidate the cache (and KV f configured):
If any of the following conditions are truthy it will avoid the cache
The revalidation process uses the waitUntil
cloudflare function in order to be executed in the background and not to block the main response to be delivered.
If the request need to be revalidated, the function will always return the stale response unless the swr
option is set to false at the request level.
Use the fetcher as a normal fetch function, but with a last argument which will tell the isr config.
interface ISRConfig {
duration: duration;
forceRefresh?: boolean;
avoidCache?: boolean;
swr?: boolean;
}
type duration = `${number} ${"second" | "minute" | "hour" | "day" | "week" | "month" | "year"}${"s" | ""}` | number;
// routes/+page.server.ts
import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ locals }) => {
const posts = await locals.fetch("https://api.example.com/posts", { duration: "1 day" });
return {
posts
};
};
// src/hooks.server.ts
// Simple example
import { Handle } from "@sveltejs/kit";
import { isr } from "sveltekit-cloudflare-isr";
export const handle: Handle = isr({ key: "fetch" });
// src/hooks.server.ts
// Complex example
import { Handle } from "@sveltejs/kit";
import { isr } from "sveltekit-cloudflare-isr";
export const handle: Handle = isr({
key: "fetch",
longTermCacheDuration: "1 year",
longTermKVDuration: "1 year",
KVNamespace: "CACHE",
shouldRefreshCache: ({ event }) => {
return event.request.headers.has("refresh-cache");
},
shouldAvoidCache: ({ event }) => {
return event.cookies.get("DATA-PREVIEW") === "true";
},
cacheName: "default"
});