### Create and Install RedwoodJS Drizzle Example Project
Source: https://github.com/redwoodjs/example-drizzle/blob/main/README.md
Steps to initialize a new RedwoodJS project using the Drizzle ORM example template, clone it, and install dependencies. This sets up the foundational structure for your application.
```shell
npx degit redwoodjs/example-drizzle my-project-name
cd my-project-name
pnpm install
```
--------------------------------
### Cloudflare Credentials Setup (Bash)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Demonstrates how to set up Cloudflare credentials for local development and D1 database migrations by creating a `.env` file from an `.env.example` template. It lists the required environment variables: CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_DATABASE_ID, and CLOUDFLARE_D1_TOKEN, along with instructions on where to find these values in the Cloudflare dashboard.
```bash
# .env.example → .env
CLOUDFLARE_ACCOUNT_ID=your-account-id
CLOUDFLARE_DATABASE_ID=your-database-id
CLOUDFLARE_D1_TOKEN=your-api-token
# Get credentials from Cloudflare Dashboard:
# - Account ID: Workers & Pages section
# - Database ID: Output from `wrangler d1 create` command
# - API Token: User Profile > API Tokens (Permissions: Account Settings:Read, D1:Edit)
```
--------------------------------
### Run RedwoodJS Development Server
Source: https://github.com/redwoodjs/example-drizzle/blob/main/README.md
Command to start the RedwoodJS development server. After running, access the application via the provided URL, typically http://localhost:5173/, to see the 'Hello World' message.
```shell
pnpm dev
```
--------------------------------
### Cloudflare D1 Database Environment Variables
Source: https://github.com/redwoodjs/example-drizzle/blob/main/README.md
Example environment variables required for Cloudflare D1 integration. These are typically placed in a `.env` file. Replace placeholders with your actual Cloudflare Account ID, Database ID, and API Token.
```text
CLOUDFLARE_ACCOUNT_ID=your-account-id
CLOUDFLARE_DATABASE_ID=your-database-id
CLOUDFLARE_D1_TOKEN=your-api-token
```
--------------------------------
### Create a Cloudflare D1 Database
Source: https://github.com/redwoodjs/example-drizzle/blob/main/README.md
Shell command to create a new D1 database on Cloudflare. The output will contain a 'database_id' which needs to be copied and used in your `wrangler.jsonc` and `.env` files.
```shell
npx wrangler d1 create my-project-db
```
--------------------------------
### Server-Side Page with Drizzle Database Queries (TypeScript)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Creates a React page component that fetches data from a D1 database server-side using Drizzle ORM before rendering. It accesses the database via the 'ctx.db' context provided by the worker setup. Requires 'rwsdk/worker' and the Drizzle schema definition.
```typescript
import { users } from "../../db/schema";
import { RequestInfo } from "rwsdk/worker";
const Home = async ({ ctx }: RequestInfo) => {
const allUsers = await ctx.db.select().from(users).all();
return (
Hello World
{JSON.stringify(allUsers, null, 2)}
);
};
export { Home };
// Expected output when accessing /:
// HTML page showing "Hello World" with JSON array of users
// Example: [{ "id": 1, "name": "John", "email": "john@example.com" }]
```
--------------------------------
### Client-Side Initialization (TypeScript)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Initializes the client-side behavior for a RedwoodJS application after server-side rendering. This file imports and calls the `initClient` function from the `rwsdk/client` module. It's responsible for hydrating the React application in the browser, making it interactive.
```typescript
// src/client.tsx
import { initClient } from "rwsdk/client";
initClient();
// This file runs in the browser after server-side rendering
// It hydrates the React application for interactivity
// No additional configuration needed for basic setup
```
--------------------------------
### Cloudflare Workers and D1 CLI Commands (Bash)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Provides essential command-line interface (CLI) commands for managing Cloudflare D1 databases and deploying workers. This includes creating a D1 database, applying migrations to a database, and deploying the worker application using npm scripts.
```bash
# Create D1 database
npx wrangler d1 create drizzle
# Apply migrations to production
npx wrangler d1 migrations apply DB
# Deploy to Cloudflare Workers
npm run release
```
--------------------------------
### Drizzle ORM Database Migration Commands
Source: https://github.com/redwoodjs/example-drizzle/blob/main/README.md
Commands for managing database schema migrations with Drizzle ORM in a RedwoodJS project. Use `pnpm migrate:new` to create a new migration file and `pnpm migrate:dev` to apply it to the database.
```shell
pnpm migrate:new
pnpm migrate:dev
```
--------------------------------
### Drizzle Configuration for D1 (TypeScript)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Configures Drizzle Kit for schema migrations with Cloudflare D1. This file specifies the output directory for migrations, the schema file location, the dialect (sqlite), and the driver ('d1-http'). It also includes credentials for connecting to the D1 database, which are typically loaded from environment variables.
```typescript
// drizzle.config.ts
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/db/schema.ts',
dialect: 'sqlite',
driver: 'd1-http',
dbCredentials: {
accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
databaseId: process.env.CLOUDFLARE_DATABASE_ID!,
token: process.env.CLOUDFLARE_D1_TOKEN!,
},
});
// Commands:
// npm run migrate:new - Generate migration files from schema changes
// npm run migrate:dev - Apply migrations to local D1 database
```
--------------------------------
### Set Security Headers Middleware (TypeScript)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Applies essential security headers to all routes in a RedwoodJS application. It uses middleware to add headers like Strict-Transport-Security, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, and Content-Security-Policy. This middleware is intended to be used in the application's router setup.
```typescript
// src/app/headers.ts
import { RouteMiddleware } from "rwsdk/router";
import { IS_DEV } from "rwsdk/constants";
export const setCommonHeaders =
(): RouteMiddleware =>
({ headers, rw: { nonce } }) => {
if (!IS_DEV) {
// Forces browsers to always use HTTPS for a specified time period (2 years)
headers.set(
"Strict-Transport-Security",
"max-age=63072000; includeSubDomains; preload"
);
}
// Forces browser to use the declared content-type instead of trying to guess/sniff it
headers.set("X-Content-Type-Options", "nosniff");
// Stops browsers from sending the referring webpage URL in HTTP headers
headers.set("Referrer-Policy", "no-referrer");
// Explicitly disables access to specific browser features/APIs
headers.set(
"Permissions-Policy",
"geolocation=(), microphone=(), camera=()"
);
// Defines trusted sources for content loading and script execution:
headers.set(
"Content-Security-Policy",
`default-src 'self'; script-src 'self' 'nonce-${nonce}' https://challenges.cloudflare.com; style-src 'self' 'unsafe-inline'; frame-src https://challenges.cloudflare.com; object-src 'none';`
);
};
// Usage in worker.tsx:
// defineApp([setCommonHeaders(), ...other middleware])
```
--------------------------------
### Configure Cloudflare D1 Database in wrangler.jsonc
Source: https://github.com/redwoodjs/example-drizzle/blob/main/README.md
Configuration file for Cloudflare Workers, specifying D1 database details such as binding name, database name, ID, and migration directory. Ensure 'YOUR-DB-ID-HERE' is replaced with your actual D1 database ID.
```jsonc
{
"name": "my-project-name",
"main": "src/worker.tsx",
"compatibility_date": "2024-09-23",
"compatibility_flags": ["nodejs_compat"],
"d1_databases": [
{
"binding": "DB",
"database_name": "my-project-db",
"database_id": "YOUR-DB-ID-HERE",
"migrations_dir": "drizzle"
}
]
}
```
--------------------------------
### Configure Cloudflare Worker with Drizzle DB Integration (TypeScript)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Sets up the Cloudflare Worker application using RedwoodSDK, integrating Drizzle ORM with a D1 database. It configures middleware for setting common headers and initializes the database context for request handling. Relies on 'rwsdk/worker', 'rwsdk/router', and 'drizzle-orm/d1'.
```typescript
import { defineApp } from "rwsdk/worker";
import { index, render } from "rwsdk/router";
import { Document } from "@/app/Document";
import { Home } from "src/pages/Home";
import { setCommonHeaders } from "src/headers";
import { drizzle } from "drizzle-orm/d1";
import { env } from "cloudflare:workers";
export interface Env {
DB: D1Database;
}
export type AppContext = {
db: ReturnType;
};
export default defineApp([
setCommonHeaders(),
async ({ ctx, request, headers }) => {
// setup db
ctx.db = drizzle(env.DB);
},
render(Document, [index([Home])]),
]);
// Expected output: Worker starts and binds to D1 database
// All routes receive ctx.db for database operations
```
--------------------------------
### Drizzle ORM User Schema Definition
Source: https://github.com/redwoodjs/example-drizzle/blob/main/README.md
TypeScript code defining a 'users' table schema using Drizzle ORM and Cloudflare D1. It includes fields like id, name, email, and createdAt, with constraints and default values.
```typescript
import { sqliteTable, text, integer, sql } from "drizzle-orm/sqlite-core";
export const users = sqliteTable("users", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
});
```
--------------------------------
### Database Seeding Script for Cloudflare Workers (TypeScript)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
A worker script designed to populate the D1 database with initial data. It uses Drizzle ORM to insert values into defined tables and then logs the completion and result. Requires 'rwsdk/worker', 'drizzle-orm/d1', and the schema definition.
```typescript
import { defineScript } from "rwsdk/worker";
import { drizzle } from "drizzle-orm/d1";
import { users } from "./schema";
export default defineScript(async ({ env }) => {
const db = drizzle(env.DB);
// Insert a user
await db.insert(users).values({
name: "__change me__",
email: "__change me__",
});
// Verify the insert by selecting all users
const result = await db.select().from(users).all();
console.log("🌱 Finished seeding");
return Response.json(result);
});
// Run: npm run seed
// Expected output: Console logs seed completion, returns JSON array of inserted users
```
--------------------------------
### HTML Document Template (TypeScript)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Defines the base HTML structure for server-rendered React applications in a RedwoodJS project. It includes essential meta tags, links to stylesheets and client-side scripts, and a root div for React hydration. This component serves as the main layout for all pages.
```typescript
// src/app/Document.tsx
export const Document: React.FC<{ children: React.ReactNode }> = ({
children,
}) => (
@redwoodjs/starter-drizzle
{children}
);
// Usage: Wraps all page content in worker.tsx render() call
// Provides hydration target (#root) and client-side JavaScript
```
--------------------------------
### Cloudflare Workers Deployment Configuration (JSON)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Defines the deployment configuration for Cloudflare Workers, including the worker's name, main entry point, compatibility settings, asset bindings, and D1 database bindings. This JSON file is used by Wrangler to build and deploy the worker to Cloudflare's edge network.
```json
// wrangler.jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "drizzle",
"main": "src/worker.tsx",
"compatibility_date": "2024-09-23",
"compatibility_flags": ["nodejs_compat"],
"assets": {
"binding": "ASSETS",
"directory": "public"
},
"d1_databases": [
{
"binding": "DB",
"database_name": "drizzle",
"database_id": "your-database-id-here",
"migrations_dir": "drizzle"
}
],
"observability": {
"enabled": true
},
"vars": {
// Add your environment variables here
}
}
```
--------------------------------
### Type-Safe CRUD with Drizzle ORM (TypeScript)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Performs type-safe SELECT, INSERT, UPDATE, and DELETE operations using Drizzle ORM with a D1 database. Initializes the Drizzle instance and demonstrates common query patterns with conditions and returning values. Assumes Drizzle schema and Cloudflare D1 bindings are configured.
```typescript
import { drizzle } from "drizzle-orm/d1";
import { users } from "./db/schema";
import { eq, like, and } from "drizzle-orm";
// Initialize in middleware/route handler
const db = drizzle(env.DB);
// SELECT with conditions
const activeUsers = await db
.select()
.from(users)
.where(like(users.email, "%@example.com"))
.all();
// INSERT with returning
const [newUser] = await db
.insert(users)
.values({ name: "Charlie", email: "charlie@test.com" })
.returning();
// UPDATE
await db
.update(users)
.set({ name: "Charlie Updated" })
.where(eq(users.id, newUser.id));
// DELETE
await db.delete(users).where(eq(users.id, newUser.id));
// Expected: Type-safe queries with IntelliSense
// Returns: Array of user objects matching schema types
```
--------------------------------
### Define SQLite Table Schemas with Drizzle ORM (TypeScript)
Source: https://context7.com/redwoodjs/example-drizzle/llms.txt
Defines SQLite table schemas using Drizzle ORM's schema builder with type-safe column definitions. Supports creating tables like 'users' and 'posts' with various column types and constraints. Requires Drizzle ORM and its SQLite core.
```typescript
import { int, sqliteTable, text } from "drizzle-orm/sqlite-core";
export const users = sqliteTable("users", {
id: int().primaryKey({ autoIncrement: true }),
name: text().notNull(),
email: text().notNull().unique(),
});
// Usage: Create additional tables
export const posts = sqliteTable("posts", {
id: int().primaryKey({ autoIncrement: true }),
title: text().notNull(),
content: text().notNull(),
authorId: int().notNull().references(() => users.id),
createdAt: int({ mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.