Skip to content

Instantly share code, notes, and snippets.

@thenetaji
Last active February 15, 2025 05:08
Show Gist options
  • Select an option

  • Save thenetaji/bf831e69693bccbd5785fbe6421c321c to your computer and use it in GitHub Desktop.

Select an option

Save thenetaji/bf831e69693bccbd5785fbe6421c321c to your computer and use it in GitHub Desktop.
Using cloudflare d1 outside workers
import Cloudflare from "cloudflare";
import "dotenv/config";
const api_token = process.env.CLOUDFLARE_D1_ACCESS_TOKEN;
const account_id = process.env.CLOUDFLARE_ACCOUNT_ID;
const database_id = process.env.CLOUDFLARE_DB_ID;
const client = new Cloudflare({ apiToken: api_token });
async function runQuery(sql, params = []) {
const res = await client.d1.database.query(database_id, { account_id, sql, params });
console.log(res);
return res;
}
// Example: Create a table
runQuery(`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT);`);
// Example: Insert data
runQuery(`INSERT INTO users (id, name) VALUES (?, ?)`, [1, "Alice"]);
// Example: Fetch data
runQuery(`SELECT * FROM users`).then(console.log);

Cloudflare D1 with Node.js (Outside Workers & Pages)

Setup

  1. Install dependencies:

npm install cloudflare dotenv

  1. Create a .env file:

CLOUDFLARE_D1_ACCESS_TOKEN=your_api_token CLOUDFLARE_ACCOUNT_ID=your_account_id CLOUDFLARE_DB_ID=your_database_id


Now you can execute SQL queries in Cloudflare D1 from your Node.js app.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment