SvelteKit ↗ is a full-stack framework that combines the Svelte front-end framework with Vite for server-side capabilities and rendering. You can query D1 from SvelteKit by configuring a server endpoint ↗ with a binding to your D1 database(s).
To set up a new SvelteKit site on Cloudflare Pages that can query D1:
- Refer to the SvelteKit guide and Svelte's Cloudflare adapter ↗.
- Install the Cloudflare adapter within your SvelteKit project:
npm i -D @sveltejs/adapter-cloudflare. - Bind a D1 database to your Pages Function.
- Pass the
--d1 BINDING_NAME=DATABASE_IDflag towrangler devwhen developing locally.BINDING_NAMEshould match what call in your code, andDATABASE_IDshould match thedatabase_iddefined in your Wrangler configuration file: for example,--d1 DB=xxxx-xxxx-xxxx-xxxx-xxxx.
The following example shows you how to create a server endpoint configured to query D1.
- Bindings are available on the
platformparameter passed to each endpoint, viaplatform.env.BINDING_NAME. - With SvelteKit's file-based routing ↗, the server endpoint defined in
src/routes/api/users/+server.tsis available at/api/userswithin your SvelteKit app.
The example also shows you how to configure both your app-wide types within src/app.d.ts to recognize your D1Database binding, import the @sveltejs/adapter-cloudflare adapter into svelte.config.js, and configure it to apply to all of your routes.
import type { RequestHandler } from "@sveltejs/kit";
export async function GET({ request, platform }) {
try {
let result = await platform.env.DB.prepare(
"SELECT * FROM users LIMIT 5",
).run();
return new Response(JSON.stringify(result), {
headers: { "Content-Type": "application/json" },
});
} catch (error) {
return Response.json({ error: "Failed to fetch users" }, {
status: 500
});
}
}// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Platform {
env: {
DB: D1Database;
};
context: {
waitUntil(promise: Promise<any>): void;
};
caches: CacheStorage & { default: Cache };
}
}
}
export {};import adapter from "@sveltejs/adapter-cloudflare";
export default {
kit: {
adapter: adapter({
// See below for an explanation of these options
routes: {
include: ["/*"],
exclude: ["<all>"],
},
}),
},
};