Query D1 from Remix
Note
Remix is no longer recommended for new projects. For new applications, use React Router instead. If you have an existing Remix application, consider migrating to React Router.
Remix is a full-stack web framework that operates on both client and server. You can query your D1 database(s) from Remix using Remix's data loading API with the useLoaderData hook.
To set up a new Remix site on Cloudflare Pages that can query D1:
- Refer to the Remix guide.
- Bind a D1 database to your Pages Function.
- Pass the
--d1 BINDING_NAME=DATABASE_IDflag towrangler devwhen developing locally.BINDING_NAMEshould match what call in your code, andDATABASE_IDshould match thedatabase_iddefined in your Wrangler configuration file: for example,--d1 DB=xxxx-xxxx-xxxx-xxxx-xxxx.
The following example shows you how to define a Remix loader that has a binding to a D1 database.
- Bindings are passed through on the
context.cloudflare.envparameter passed to aLoaderFunction. - If you configured a binding named
DB, then you would access D1 Workers Binding API methods viacontext.cloudflare.env.DB.
import type { LoaderFunction } from "@remix-run/cloudflare";
import { json } from "@remix-run/cloudflare";
import { useLoaderData } from "@remix-run/react";
interface Env {
DB: D1Database;
}
export const loader: LoaderFunction = async ({ context, params }) => {
let env = context.cloudflare.env as Env;
try {
let { results } = await env.DB.prepare("SELECT * FROM users LIMIT 5").run();
return json(results);
} catch (error) {
return json({ error: "Failed to fetch users" }, { status: 500 });
}
};
export default function Index() {
const results = useLoaderData<typeof loader>();
return (
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
<h1>Welcome to Remix</h1>
<div>
A value from D1:
<pre>{JSON.stringify(results)}</pre>
</div>
</div>
);
}