Working with Svelte Kit and Cloudflare KV
Missing Documentation
SvelteKit is a Javascript framework that is gaining popularity for building web applications. Cloudflare Pages is one of the platforms to host SvelteKit based applications.
Cloudflare provides various distributed serverless technologies like low latency Key values store (Workers KV), persisted data store (D1) and many more.
This article explains how to integrate SvelteKit application with Workers KV in local and production environments.
A brief about Workers KV
Workers KV is a key-value distributed data storage. To begin using KV, you must create a KV namespace using Cloudflare Dashboard or Wrangler tool. A namespace is a grouping or management construct for key-value pairs.
Binding a KV namespace in the code
SvelteKit lets you specify platform-specific resources via app.d.ts
file. Consider MIGHTY_KV
is a KV resource that we wanted to link. It can be specified in app.d.ts
as:
// app.d.ts file
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Platform {
env: {
MIGHTY_KV: KVNamespace;
}
}
}
}
Using KV in code
+server.ts
,+page.server.ts
and hooks.server.ts
(server side) files provide platform
object property for accessing KV or any other Cloudflare resource as:
// +page.server.ts
export const load: PageServerLoad = async ({ params, fetch, platform }) =>{
const handler = await platform?.env.MIGHTY_KV.get("handler");
// 'get' is a KV API
// so does, 'put', 'list'
// You may refer to https://developers.cloudflare.com/kv/api/
// rest implementation
}
//+server.ts
export async function GET({ params, url, platform }) {
const handler = await platform?.env.MIGHTY_KV.get("handler");
// rest implementation
}
//hooks.server.ts
export const handle: Handle = async ({ event, resolve }) => {
const handler = await event.platform?.env.MIGHTY_KV.get("handler");
// rest implementation
}
Local Integration and testing
Wrangler is a command-line tool to manage Cloudflare resources and projects. You can install it globally (then use wrangler
command) or within the project as a dev dependency (then use npx wrangler
).
You can specify the KV in the start-up command as:
npx wrangler pages dev .svelte-kit/cloudflare --kv <namespace>
# sample
npx wrangler pages dev .svelte-kit/cloudflare --kv MIGHTY_KV=<id>
# sample with no ID
# in case you want to keep 'namespace name' = 'namespace id'
npx wrangler pages dev .svelte-kit/cloudflare --kv=MIGHTY_KV
# sample with multiple KVs
npx wrangler pages dev .svelte-kit/cloudflare --kv=MIGHTY_KV --kv ANOTHER_KV=test
KV namespace ID is irrelevant for local testing because Wrangler (when run with dev) does not connect to production KVs. It just injects emulated KVs.
Optionally, You can also specify KVs in wrangler.toml
file as
name = "dm8ty"
pages_build_output_dir = ".svelte-kit/cloudflare"
compatibility_flags = [ "nodejs_compat" ]
[[kv_namespaces]]
binding = "MIGHTY_KV"
id = "test"
then, the start-up command is brief as:
npx wrangler pages dev .svelte-kit/cloudflare
Once the application is launched, you will observe similar messages of bindings:
✨ Compiled Worker successfully
⛅️ wrangler 3.51.2
-------------------
Your worker has access to the following bindings:
- KV Namespaces:
- MIGHTY_KV: test
⎔ Starting local server...
Injecting data for local testing
To inject values into the emulated KV, follow the command:
npx wrangler kv:key put <key> <value> --local --binding MIGHTY_KV
//sample
npx wrangler kv:key put handler d8mtyprogrammer --local --binding MIGHTY_KV
Be careful when inserting value to a namespace. When using the command, include the --local
argument to avoid pushing the value to Production KV.
When does it create a file in the following path (relative to the project root):
.wrangler/state/v3/cache/kv/<namespace_id>/blobs/<key-hash>
Once you recognize the key-value file, you may change its content directly for future updates rather than using the command.
Production integration
After creating a KV namespace and a page application. You can bind the application with KV as:
Page Application > Settings > Functions > KV namespace bindings
Next?
For other Cloudflare resources like D1 and Durable Object, you can follow the similar way to development and bindings.
Footnotes
The versions of tooling are
wrangler 3.51.2
@sveltejs/kit 2.5.6