Skip to content

Query D1 from SvelteKit

Query a D1 database from a SvelteKit application.

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:

  1. 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.

  2. Configure a D1 database binding in your Wrangler configuration file. binding is the name you use in your code, and database_id is 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>"
  3. Generate TypeScript types for your bindings so that env.DB is typed as a D1Database:

    npm run cf-typegen
  4. Create a schema.sql file 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.sql
  5. Start the local development server. It reads the D1 binding from your Wrangler configuration file and uses the local database:

    npm run dev

The following example shows you how to create a server endpoint configured to query D1.

  • Bindings are available on the env object imported from cloudflare:workers, via env.BINDING_NAME.
  • With SvelteKit's file-based routing ↗︎, the server endpoint defined in src/routes/api/users/+server.ts is available at /api/users within your SvelteKit app.

The example also shows how to apply the @sveltejs/adapter-cloudflare adapter in vite.config.ts.

src/routes/api/users/+server.tsts
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 },
		);
	}
};
vite.config.tsts
import adapter from "@sveltejs/adapter-cloudflare";
import { sveltekit } from "@sveltejs/kit/vite";
import { defineConfig } from "vite";

export default defineConfig({
	plugins: [
		sveltekit({
			adapter: adapter(),
		}),
	],
});

Was this helpful?