React Router is the successor to Remix v2. It is a full-stack web framework that operates on both client and server. You can query your D1 database(s) from React Router using a loader ↗︎ function, and render the result in your route component with the loaderData prop.
To set up a React Router site on Cloudflare Workers that can query D1:
-
Create a React Router project by following the React Router Workers guide:
npm create cloudflare@latest -- my-react-router-app --framework=react-routeryarn create cloudflare my-react-router-app --framework=react-routerpnpm create cloudflare@latest my-react-router-app --framework=react-router -
Configure a D1 database binding in your Wrangler configuration file.
bindingis the name you use in your code, anddatabase_idis 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>" -
Generate TypeScript types for your bindings so that
env.DBis typed as aD1Database:npm run cf-typegenyarn run cf-typegenpnpm run cf-typegen -
Create a
schema.sqlfile 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.sqlyarn wrangler d1 execute my-database --local --file=./schema.sqlpnpm wrangler d1 execute my-database --local --file=./schema.sql -
Start the local development server. It reads the D1 binding from your Wrangler configuration file and uses the local database:
npm run devyarn run devpnpm run dev
The following example shows you how to define a React Router loader that queries a D1 database.
- Bindings are available on the
envobject imported fromcloudflare:workers. - If you configured a D1 binding named
DB, you access D1 Workers Binding API methods viaenv.DB.
import { env } from "cloudflare:workers";
import { data } from "react-router";
import type { Route } from "./+types/home";
export async function loader() {
try {
const { results } = await env.DB.prepare(
"SELECT * FROM users LIMIT 5",
).run();
return { results };
} catch (error) {
return data({ error: "Failed to fetch users" }, { status: 500 });
}
}
export default function Home({ loaderData }: Route.ComponentProps) {
return (
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
<h1>Welcome to React Router</h1>
<div>
A value from D1:
<pre>{JSON.stringify(loaderData)}</pre>
</div>
</div>
);
}