Note: 🧪 This is a example application and is not officially supported by Cloudflare.
An example SvelteKit project on Cloudflare Pages (https://developers.cloudflare.com/pages/framework-guides/deploy-a-svelte-site/) that connects to a D1 database.
There are a few things you need to do:
svelte.config.ts
to import import adapter from '@sveltejs/adapter-cloudflare'
instead of adapter-auto
src/app.d.ts
to expand the Platform
interface
to the below: interface Platform {
env: {
DB: D1Database;
};
context: {
waitUntil(promise: Promise<any>): void;
};
caches: Cache
src/app.d.ts
(in this example, it's DB
) - per https://developers.cloudflare.com/pages/platform/functions/bindings/#d1-databasesYou can then re-deploy the app. The SvelteKit documentation also has a comprehensive Cloudflare Pages tutorial.
Svelte's server endpoints allow you to define API endpoints: to access a D1 database, you want to access platform.env.BINDING_NAME.prepare
(or other D1 API methods) — no different from a non-SvelteKit app.
An example server endpoint that accesses D1 at /api/users/+server.ts
- corresponding to https://your-app.pages.dev/api/users
resembles the following:
import type { RequestHandler } from "@sveltejs/kit";
/** @type {import('@sveltejs/kit').RequestHandler} */
export async function GET({ request, platform }) {
// Matches the "DB" binding you create: make sure the names match!
let result = await platform.env.DB.prepare(
"SELECT * FROM users LIMIT 5"
).run();
return new Response(JSON.stringify(result));
}
Copyright Cloudflare, Inc (2023). Apache-2.0 licensed. See the LICENSE file for details.