This is a template for the Cloudflare C3 CLI that initializes a new SvelteKit project with a D1 database.
Key Features:
- connects to D1 database with Drizzle
- authentication with Lucia
- makes use of Remote functions in SvelteKit
- DaisyUI for styling
- valibot for form validation
pnpm create cloudflare@latest --template [email protected]:ViggieM/sveltekit-d1.git [DIRECTORY] --git
cd [DIRECTORY]
pre-commit installpnpx wrangler d1 create --binding 'DB' [DATABASE_NAME]
# update types after db creation
pnpm wrangler types ./src/worker-configuration.d.tsSet the "migrations_dir" of your recently created database in wrangler.jsonc to "drizzle".
And generate the migrations for the tables 'user' and 'session':
pnpm run db:generateCLOUDFLARE_ACCOUNT_ID
can be determined with `pnpx wrangler whoami`CLOUDFLARE_DATABASE_ID
is the one from the previous step (in `wrangler.jsonc` "d1_databases" settings)CLOUDFLARE_D1_TOKEN
- Go to Account API tokens (or User API Tokens)
- Under API Tokens, select Create Token.
- Scroll to Custom token > Create custom token, then select Get started.
- Under Token name, enter a descriptive token name. For example,
Name-D1-Import-API-Token. - Under Permissions:
- Select Account.
- Select D1.
- Select Edit.
- Select Continue to summary.
- Select Create token.
- Copy the API token and save it in a secure file. (i.e. in the
.envfile asCLOUDFLARE_D1_TOKEN)
npx wrangler secret put CLOUDFLARE_ACCOUNT_ID
npx wrangler secret put CLOUDFLARE_DATABASE_ID
npx wrangler secret put CLOUDFLARE_D1_TOKEN
# update types after secrets or env variables update
pnpm wrangler types ./src/worker-configuration.d.tspnpm drizzle-kit push
# generate migrations in the /drizzle folder
pnpm drizzle-kit generate
pnpm drizzle-kit migrate
# apply migrations locally
pnpm wrangler d1 migrations apply [DATABASE_NAME] --localpnpm build
pnpm wrangler deploy
# follow logs
pnpm wrangler tail- Add GitHub / Google authentication
- Add a 404/500 error page
- Improve logout: ATM there are two ways it is done, but I didn't decide yet which one is better
- In case you don't need any authentication, use the prompt misc/REMOVE_AUTHENTICATION_PROMPT.md
In case you encounter any issues with the worker, you can use
pnpm wrangler tailto inspect logs.
Here are some errors I encountered and their solutions:
Note that these reports were written by Claude Code, so they might contain false informations and hints. :)
No, since the access to the D1 database is configured in the drizzle.config.ts file as:
export default defineConfig({
// ...
dbCredentials: {
accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
databaseId: process.env.CLOUDFLARE_DATABASE_ID!,
token: process.env.CLOUDFLARE_D1_TOKEN!
}
// ...
});