How can I connect to my Cloudflare D1 database from a Cloudflare Worker?

Question

Grade: Education Subject: Support
How can I connect to my Cloudflare D1 database from a Cloudflare Worker?
Asked by:
72 Viewed 72 Answers

Answer (72)

Best Answer
(351)
You connect to a D1 database from a Worker using the `D1` binding in your Worker's `wrangler.toml` file. Define the database name, and then access it within your Worker code using the `D1Database` object. Example: `export type Database = D1.Database;` and then `const db = env.MY_DATABASE;` where `MY_DATABASE` is the name defined in `wrangler.toml`.