SvelteKit on Cloudflare Example
This example demonstrates deploying a SvelteKit application to Cloudflare with KV Namespace and R2 Bucket bindings.Features
- SvelteKit: Modern Svelte meta-framework
- KV Namespace: Key-value storage for auth/sessions
- R2 Bucket: Object storage
- Environment Bindings: Secrets and configuration
- Type Safety: Full TypeScript types for platform
Project Setup
import alchemy from "alchemy";
import { KVNamespace, R2Bucket, SvelteKit } from "alchemy/cloudflare";
const app = await alchemy("cloudflare-sveltekit");
const [authStore, storage] = await Promise.all([
KVNamespace("auth-store", {
title: `${app.name}-${app.stage}-auth-store`,
adopt: true,
}),
R2Bucket("storage", {
allowPublicAccess: false,
adopt: true,
name: `${app.name}-${app.stage}-storage`,
}),
]);
export const website = await SvelteKit("website", {
name: `${app.name}-${app.stage}-website`,
bindings: {
AUTH_STORE: authStore,
STORAGE: storage,
ALCHEMY_TEST_VALUE: alchemy.secret("Hello from Alchemy!"),
},
url: true,
});
console.log(website.url);
if (process.env.ALCHEMY_E2E) {
const { test } = await import("./test/e2e.js");
await test({
url: website.url,
env: { ALCHEMY_TEST_VALUE: "Hello from Alchemy!" },
});
}
await app.finalize();
import adapter from '@sveltejs/adapter-cloudflare';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
preprocess: vitePreprocess(),
kit: {
adapter: adapter(),
},
};
import type { website } from "./alchemy.run";
declare global {
namespace App {
interface Platform {
env: typeof website.Env;
}
}
}
export {};
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ platform }) => {
const env = platform?.env;
if (!env) {
throw new Error('Platform env not available');
}
// Access KV
await env.AUTH_STORE.put('last-visit', new Date().toISOString());
const lastVisit = await env.AUTH_STORE.get('last-visit');
// Access R2
await env.STORAGE.put('test.txt', 'Hello from SvelteKit!');
const file = await env.STORAGE.get('test.txt');
const content = await file?.text();
return {
message: env.ALCHEMY_TEST_VALUE,
lastVisit,
fileContent: content,
};
};
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<div>
<h1>SvelteKit on Cloudflare</h1>
<p>Message: {data.message}</p>
<p>Last Visit: {data.lastVisit}</p>
<p>File Content: {data.fileContent}</p>
</div>
import type { RequestHandler } from './$types';
import { json } from '@sveltejs/kit';
export const POST: RequestHandler = async ({ request, platform }) => {
const env = platform?.env;
if (!env) {
return json({ error: 'Platform not available' }, { status: 500 });
}
const formData = await request.formData();
const file = formData.get('file') as File;
if (!file) {
return json({ error: 'No file provided' }, { status: 400 });
}
// Upload to R2
const buffer = await file.arrayBuffer();
await env.STORAGE.put(file.name, buffer);
return json({
success: true,
filename: file.name,
size: file.size,
});
};