Skip to content

Query D1 from Remix

Query your D1 database from a Remix application.

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:

  1. Create a React Router project by following the React Router Workers guide:

    npm create cloudflare@latest -- my-react-router-app --framework=react-router
  2. Configure a D1 database binding in your Wrangler configuration file. binding is the name you use in your code, and database_id is 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>"
  3. Generate TypeScript types for your bindings so that env.DB is typed as a D1Database:

    npm run cf-typegen
  4. Create a schema.sql file 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.sql
  5. Start the local development server. It reads the D1 binding from your Wrangler configuration file and uses the local database:

    npm run dev

The following example shows you how to define a React Router loader that queries a D1 database.

  • Bindings are available on the env object imported from cloudflare:workers.
  • If you configured a D1 binding named DB, you access D1 Workers Binding API methods via env.DB.
app/routes/home.tsxtsx
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>
	);
}

Was this helpful?