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 SvelteKit site on Cloudflare Workers that can query D1:
-
Create a SvelteKit project by following the SvelteKit Workers guide. The guide installs and configures Svelte's Cloudflare adapter ↗︎. To add the adapter to an existing SvelteKit project instead, run
npm i -D @sveltejs/adapter-cloudflare. -
Configure a D1 database binding in your Wrangler configuration file.
bindingis the name you use in your code, anddatabase_idis the ID returned when you create the database:{ "d1_databases": [ { "binding": "DB", "database_name": "my-database", "database_id": "<YOUR_DATABASE_ID>", }, ], }[[d1_databases]] binding = "DB" database_name = "my-database" database_id = "<YOUR_DATABASE_ID>" -
Generate TypeScript types for your bindings so that
env.DBis typed as aD1Database:npm run cf-typegenyarn run cf-typegenpnpm run cf-typegen -
Create a
schema.sqlfile in your project root, then apply it to your local D1 database:schema.sqlsql DROP TABLE IF EXISTS users; CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT); INSERT INTO users (name) VALUES ('Alice'), ('Bob');npx wrangler d1 execute my-database --local --file=./schema.sqlyarn wrangler d1 execute my-database --local --file=./schema.sqlpnpm wrangler d1 execute my-database --local --file=./schema.sql -
Start the local development server. It reads the D1 binding from your Wrangler configuration file and uses the local database:
npm run devyarn run devpnpm run dev
The following example shows you how to create a server endpoint configured to query D1.
- Bindings are available on the
envobject imported fromcloudflare:workers, viaenv.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 how to apply the @sveltejs/adapter-cloudflare adapter in vite.config.ts.
import { env } from "cloudflare:workers";
import type { RequestHandler } from "./$types";
export const GET: RequestHandler = async () => {
try {
const { results } = await env.DB.prepare(
"SELECT * FROM users LIMIT 5",
).run();
return Response.json(results);
} catch (error) {
return Response.json(
{ error: "Failed to fetch users" },
{ status: 500 },
);
}
};import adapter from "@sveltejs/adapter-cloudflare";
import { sveltekit } from "@sveltejs/kit/vite";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
sveltekit({
adapter: adapter(),
}),
],
});