SvelteKit's loaders make it easy to keep a page supplied with fresh data, but they also make it easy to hammer a datastore on every navigation. This walkthrough builds a searchable to-do list that caches endpoint responses, purges them on mutation, and even patches the UI without re-running the page's loader — using only SvelteKit and browser primitives, no extra libraries.
A caveat before the code: these techniques reproduce features you'd normally get from a data utility, and they add real complexity to your application. If your data store responds quickly and your UI tolerates SvelteKit always fetching what each page needs, stop there and enjoy the simplicity. Reach for the tricks below only when that stops being true.
Preparing the example
Two structural changes set things up. First, move data loading out of the +page.server.js loader and into an API route: create +server.js in routes/api/todos with a GET function, which makes the data available at /api/todos to the browser's default GET verb.
import { json } from "@sveltejs/kit";
import { getTodos } from "$lib/data/todoData";
export async function GET({ url, setHeaders, request }) {
const search = url.searchParams.get("search") || "";
const todos = await getTodos(search);
return json(todos);
}
Second, rename the page loader from +page.server.js to +page.js (or .ts in a TypeScript project), turning it into a universal loader. Universal loaders run on the server during the initial load and in the browser afterwards, so once the first load is done the fetch to the endpoint is the browser's native fetch — exactly where HTTP caching applies.
export async function load({ fetch, url, setHeaders }) {
const search = url.searchParams.get("search") || "";
const resp = await fetch(`/api/todos?search=${encodeURIComponent(search)}`);
const todos = await resp.json();
return {
todos,
};
}
A plain form on the /list page submits a search term to the page loader. The term lands in the query string, which re-runs the loader and filters the to-do items.
<div class="search-form">
<form action="/list">
<label>Search</label>
<input autofocus name="search" />
</form>
</div>

Also bump the artificial delay in todoData.js under /lib/data so it's obvious when data comes from cache and when it doesn't.
export const wait = async amount => new Promise(res => setTimeout(res, amount ?? 500));
Adding HTTP caching
The endpoint gets a single Cache-Control header, which instructs the browser to keep responses for 60 seconds. Tune the window to your use case; depending on the workload, stale-while-revalidate may also be worth a look.
setHeaders({
"cache-control": "max-age=60",
});
The full function:
export async function GET({ url, setHeaders, request }) {
const search = url.searchParams.get("search") || "";
setHeaders({
"cache-control": "max-age=60",
});
const todos = await getTodos(search);
return json(todos);
}
Search results now come from the cache — provided the "disable cache" checkbox in DevTools is unchecked.

Who caches what
- Initial server load. If the first navigation in the app is the list page, the loader runs on the server, SvelteKit serializes the result and sends it to the client, and it records the response's
Cache-Controlheader so that endpoint call is served from that cached data for the rest of the window. These results are cached inside SvelteKit, so DevTools shows nothing when you return to that search. - Subsequent client-side searches. Searches made on the page after the initial load produce real browser requests to
/api/todos. Repeat a search within 60 seconds and the response is instant. Because the caching is the browser's own, these entries can survive a page reload, unlike the server-side load, which always calls the endpoint fresh.
Data can change at any moment, so the cache needs a manual purge path.
A cache-busting cookie
The purge mechanism is a value appended to requests to /api/todos, stored in a cookie so it can be written on the server and read on the client. A +layout.server.js at the root of routes runs at application startup and is a natural place to set the initial value.
export function load({ cookies, isDataRequest }) {
const initialRequest = !isDataRequest;
const cacheValue = initialRequest ? +new Date() : cookies.get("todos-cache");
if (initialRequest) {
cookies.set("todos-cache", cacheValue, { path: "/", httpOnly: false });
}
return {
todosCacheBust: cacheValue,
};
}
The isDataRequest flag matters: layouts re-run whenever client code calls invalidate() or a server action runs, and the cookie should only be set on a genuine startup (isDataRequest is false), passing the existing value through otherwise. The httpOnly: false flag lets client code read the value from document.cookie; normally a security concern, but here the value is a meaningless number used only for caching decisions.
Reading and sending the value
The universal loader must find this value on either side. On the server it can call await parent() to get data from parent layouts; on the client it parses document.cookie. That parsing is needed only once.
export function getCookieLookup() {
if (typeof document !== "object") {
return {};
}
return document.cookie.split("; ").reduce((lookup, v) => {
const parts = v.split("=");
lookup[parts[0]] = parts[1];
return lookup;
}, {});
}
const getCurrentCookieValue = name => {
const cookies = getCookieLookup();
return cookies[name] ?? "";
};
The loader then appends the value to the endpoint URL.
import { getCurrentCookieValue } from "$lib/util/cookieUtils";
export async function load({ fetch, parent, url, setHeaders }) {
const parentData = await parent();
const cacheBust = getCurrentCookieValue("todos-cache") || parentData.todosCacheBust;
const search = url.searchParams.get("search") || "";
const resp = await fetch(`/api/todos?search=${encodeURIComponent(search)}&cache=${cacheBust}`);
const todos = await resp.json();
return {
todos,
};
}
getCurrentCookieValue('todos-cache') detects the client by checking the type of document and returns nothing there; when it returns nothing, the loader knows it is on the server and uses the layout's value.
Invalidating
Any server action can rotate the value, which invalidates every cached entry derived from the old one:
cookies.set("todos-cache", cacheValue, { path: "/", httpOnly: false });
Wiring up an edit flow
Add editing to the list page: each to-do gets a second table row containing an edit form.
import { enhance } from "$app/forms";
<tr>
<td colspan="4">
<form use:enhance method="post" action="?/editTodo">
<input name="id" value="{t.id}" type="hidden" />
<input name="title" value="{t.title}" />
<button>Save</button>
</form>
</td>
</tr>
Form actions live only in .server files, so add +page.server.js inside the /list folder — a +page.server.js and a +page.js can sit side by side. The action reads the form data, applies the artificial delay, updates the to-do, and rotates the cache-bust cookie.
import { getTodo, updateTodo, wait } from "$lib/data/todoData";
export const actions = {
async editTodo({ request, cookies }) {
const formData = await request.formData();
const id = formData.get("id");
const newTitle = formData.get("title");
await wait(250);
updateTodo(id, newTitle);
cookies.set("todos-cache", +new Date(), { path: "/", httpOnly: false });
},
};
With that in place, editing a to-do updates the table shortly afterwards; the Network tab shows a fetch to /api/todos returning the new data. This is the default behavior at work.

Updating the screen without a refetch
Skipping that post-edit fetch is about correctness as much as speed. Search for "post", then remove that word from one of the listed items: after the edit the item disappears, because it no longer matches the current search. If you'd rather not re-run the page's loader while still clearing the cache and showing the edit, change the loader to return the to-dos inside a writable store instead of as plain data.
return {
todos: writable(todos),
};
The old approach read data, a prop you don't own and can't update; a store returned from a universal loader is yours to mutate. The page just needs a small adjustment to consume the store.
{#each todos as t}
{#each $todos as t}
To intercept the submit, give use:enhance a function:
<form
use:enhance={executeSave}
on:submit={runInvalidate}
method="post"
action="?/editTodo"
>
function executeSave({ data }) {
const id = data.get("id");
const title = data.get("title");
return async () => {
todos.update(list =>
list.map(todo => {
if (todo.id == id) {
return Object.assign({}, todo, { title });
} else {
return todo;
}
})
);
};
}
That function receives the form data and returns an async function that runs after the edit completes. Returning it suppresses SvelteKit's default form handling, which would have re-run the loader — precisely the outcome we want, and one the docs show how to restore if needed. Inside the callback, call update on the todos store so the edit appears immediately. The cache is still cleared, because the editTodo action sets a new cookie value; searching and returning to the page fetches fresh data that correctly excludes the updated item.
Scope and alternatives
Cookies can be set in any server load function or action, not only the root layout, so data used under a single layout or page can keep its bust value closer to where it's needed. If you don't do the on-screen store update and simply want the loader to re-run after a mutation, set a fresh cookie value in that loader with no isDataRequest check: it sets on the first run, and every server action on that page then invalidates the layout and re-runs the loader, rotating the bust string before the universal loader is called.
A reload button, narrowly scoped
The last feature clears the cache and re-runs the current query. A minimal form action rotates the cookie (a real project would factor out the repeated cookie-setting code).
async reloadTodos({ cookies }) {
cookies.set('todos-cache', +new Date(), { path: '/', httpOnly: false });
},
<form method="POST" action="?/reloadTodos" use:enhance>
<button>Reload todos</button>
</form>

Two improvements: show the user that a reload is underway, and stop SvelteKit from invalidating everything. By default an action invalidates every layout and page in the current hierarchy, including data loaded once in the root layout that needn't be reloaded. Passing a function to enhance narrows the blast radius.
<form method="POST" action="?/reloadTodos" use:enhance={reloadTodos}>
import { enhance } from "$app/forms";
import { invalidate } from "$app/navigation";
let reloading = false;
const reloadTodos = () => {
reloading = true;
return async () => {
invalidate("reload:todos").then(() => {
reloading = false;
});
};
};
A reloading flag goes to true when the action starts. The returned async function, by existing, stops the default blanket invalidation, so we call invalidate('reload:todos') ourselves; the promise it returns resolves when invalidation finishes, and reloading flips back. The loader pairs with this via depends:
export async function load({ fetch, url, setHeaders, depends }) {
depends('reload:todos');
// rest is the same
depends and invalidate accept more than custom labels: pass a URL and SvelteKit tracks which loaders depend on it. So depends can be skipped in favor of invalidating the /api/todos endpoint, at the cost of supplying the exact URL including the search term and cache value — or matching on path name:
invalidate(url => url.pathname == "/api/todos");
The depends version is more explicit and simpler to read, but the choice is yours.
Takeaways
The pieces here are web platform primitives — Cache-Control headers and cookies — plus SvelteKit's loader, action, depends and invalidate machinery, and they transfer well beyond SvelteKit. They are also optional. When your datastore is fast and scaling isn't a problem, shipping this machinery is needless complexity; write clear, simple code and add these tools only when you actually need them.



