SvelteKit and Cloudflare D1
SvelteKit and Cloudflare D1
This guide will provide a step-by-step process for building and deploying a SvelteKit application with Cloudflare D1 and TypeSQL.
-
Setting up a new project
Terminal window npm create cloudflare@latest -- my-svelte-app --framework=svelteSee: https://developers.cloudflare.com/pages/framework-guides/deploy-a-svelte-site/
Install wrangler and TypeSQL as dev dependencies:
Terminal window npm install --save-dev wrangler typesql-cliCreate the typesql.json config file:
Terminal window npx typesql initChange the
typesql.json
:typesql.json {"databaseUri": "./mydb.db","sqlDir": "./src/server/sql","client": "d1","includeCrudTables": []}After you have installed the project dependencies, start the application:
Terminal window npm run dev -
Create the d1 Database
Terminal window npx wrangler d1 create my-d1-databasePaste the result in the wrangle.toml file:
[[d1_databases]]binding = "DB"database_name = "my-d1-database"database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" -
Update
src/app.d.ts
to expand the Platform interface to the below:
declare global { namespace App { interface Platform { env: { DB: D1Database; }; cf: CfProperties; ctx: ExecutionContext; } }}
- Create a migration:
npx wrangler d1 migrations create my-d1-database create-initial-schema
- Create the database schema:
PS: If you are using VSCode and want to have autocompletion for SQL, install the TypeSQL Language Server extension.
CREATE TABLE users( id INTEGER PRIMARY KEY, username TEXT NOT NULL);
CREATE TABLE posts( id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL, user_id INTEGER NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id));
- Apply the migrations locally:
npx wrangler d1 migrations apply my-d1-database --local
- Change the
databaseUri
in thetypesql.json
:
{ "databaseUri": "./.wrangler/state/v3/d1/miniflare-D1DatabaseObject/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.sqlite", "sqlDir": "./src/server/sql", "client": "d1", "includeCrudTables": []}
- Write your queries:
SELECT *FROM postsWHERE user_id = :user_id
- Generate the code with TypeSQL:
npx typesql compile -w
- Show the data:
// src/routes/+page.server.tsexport const load: PageServerLoad = async ({ platform }) => { const posts = await selectUserPosts(platform!.env.DB, { user_id: 1, }); return { posts, };};
// src/routes/+page.svelte<script lang="ts"> import type { PageData } from "./$types"; let { data }: { data: PageData } = $props();</script><h1>Posts</h1><ul> {#each data.posts as post} <li>{post.title}</li> {/each}</ul>
- Deploy:
bunx wrangler d1 migrations apply my-d1-database --remotenpm run deploy