### Next Steps After Project Creation Source: https://docs.rwsdk.com/reference/create-rwsdk After successfully creating a project, navigate into the project directory, install dependencies, and start the development server. ```bash cd pnpm install pnpm dev ``` -------------------------------- ### Install React Email Preview Source: https://docs.rwsdk.com/guides/email/email-templates Install the React Email Preview tool to get a starter project and preview your emails. ```bash npx create-email@latest cd react-email-starter pnpm install pnpm dev ``` -------------------------------- ### Run Storybook Server with Bun Source: https://docs.rwsdk.com/guides/frontend/storybook Start the Storybook development server using Bun. Ensure Storybook is installed in your project. ```bash bun run storybook ``` -------------------------------- ### Complete SEO Setup with Meta Tags Source: https://docs.rwsdk.com/guides/frontend/metadata Implement a comprehensive SEO setup including Open Graph and Twitter card meta tags, along with basic meta tags and a canonical URL. This example demonstrates how to dynamically set meta tags based on post data. ```jsx import React from "react"; export default function BlogPostPage({ post }) { const { title, description, image, publishDate, author } = post; return ( <> {/* Basic Meta Tags */} {title} | My Blog {/* Open Graph / Facebook */} {/* Twitter */} {/* Canonical URL */} {/* Page Content */}

{title}

{/* Rest of your blog post content */}
); } ``` -------------------------------- ### Run Storybook Server with npm Source: https://docs.rwsdk.com/guides/frontend/storybook Start the Storybook development server using npm. Ensure Storybook is installed in your project. ```bash npm run storybook ``` -------------------------------- ### Run Storybook Server with pnpm Source: https://docs.rwsdk.com/guides/frontend/storybook Start the Storybook development server using pnpm. Ensure Storybook is installed in your project. ```bash pnpm run storybook ``` -------------------------------- ### Install Project Dependencies Source: https://docs.rwsdk.com/getting-started/quick-start Navigate to your project directory and install the necessary dependencies using your preferred package manager. ```bash cd my-project-name ``` ```bash npm install ``` ```bash yarn install ``` ```bash pnpm install ``` ```bash bun install ``` -------------------------------- ### Install Chakra UI with bun Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Use this command to install the necessary Chakra UI packages using bun. ```bash bun add @chakra-ui/react @emotion/react ``` -------------------------------- ### Run Storybook Server with Yarn Source: https://docs.rwsdk.com/guides/frontend/storybook Start the Storybook development server using Yarn. Ensure Storybook is installed in your project. ```bash yarn run storybook ``` -------------------------------- ### Install Storybook with bun Source: https://docs.rwsdk.com/guides/frontend/storybook Use this command to create a new Storybook project with bun. ```bash bun create storybook@latest ``` -------------------------------- ### Install React Email and Resend Source: https://docs.rwsdk.com/guides/email/email-templates Install both React Email components and Resend in one command. ```bash pnpm add @react-email/components resend ``` -------------------------------- ### Basic Setup: Import initClient Source: https://docs.rwsdk.com/guides/frontend/error-handling Shows the initial step of importing the `initClient` function from the `rwsdk/client` module. ```typescript import { initClient } from "rwsdk/client"; ``` -------------------------------- ### Start Development Server Source: https://docs.rwsdk.com/guides/debugging Run this command in your terminal to start the development server, which is necessary before attaching the debugger to server-side code. ```bash npm run dev ``` -------------------------------- ### Install Chakra UI with yarn Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Use this command to install the necessary Chakra UI packages using yarn. ```bash yarn add @chakra-ui/react @emotion/react ``` -------------------------------- ### Run Development Server with bun Source: https://docs.rwsdk.com/guides/frontend/ark-ui Command to start the development server using bun. ```bash bun run dev ``` -------------------------------- ### Install Chakra UI with npm Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Use this command to install the necessary Chakra UI packages using npm. ```bash npm install @chakra-ui/react @emotion/react ``` -------------------------------- ### Install Storybook with yarn Source: https://docs.rwsdk.com/guides/frontend/storybook Use this command to create a new Storybook project with yarn. ```bash yarn create storybook@latest ``` -------------------------------- ### Install Chakra UI with pnpm Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Use this command to install the necessary Chakra UI packages using pnpm. ```bash pnpm add @chakra-ui/react @emotion/react ``` -------------------------------- ### Install Storybook with npm Source: https://docs.rwsdk.com/guides/frontend/storybook Use this command to create a new Storybook project with npm. ```bash npm create storybook@latest ``` -------------------------------- ### Install RedwoodSDK Source: https://docs.rwsdk.com/guides/optimize/react-compiler Install the latest version of RedwoodSDK using pnpm. ```bash pnpm add rwsdk@latest ``` -------------------------------- ### Install React Email Components Source: https://docs.rwsdk.com/guides/email/email-templates Install the React Email components to your project. This assumes Resend is already installed. ```bash pnpm add @react-email/components ``` -------------------------------- ### Mock Prisma Client Setup Source: https://docs.rwsdk.com/guides/frontend/storybook Defines a mock Prisma client and a setup function to provide test-specific mocks. This is crucial for isolating components during testing. ```typescript /** * First, mock the imported client. */ export let db: unknown; /** * Then, create a function to set the mock client. * We do this so that that we can have test-specific mocks, * rather than having only one version of the mocked client. * * @param [dbMock={}] An object to use as the mock client. Be sure to mock any Prisma functions used by the component we're testing. */ export function setupDb(dbMock: unknown = {}) { db = dbMock; } ``` -------------------------------- ### Install Resend Package Source: https://docs.rwsdk.com/guides/email/sending-email Install the Resend package using pnpm. This command adds the necessary library to your project. ```bash pnpm add resend ``` -------------------------------- ### Install Storybook with pnpm Source: https://docs.rwsdk.com/guides/frontend/storybook Use this command to create a new Storybook project with pnpm. ```bash pnpm create storybook@latest ``` -------------------------------- ### Run Development Server with pnpm Source: https://docs.rwsdk.com/guides/frontend/ark-ui Command to start the development server using pnpm. ```bash pnpm run dev ``` -------------------------------- ### Install Drizzle Packages Source: https://docs.rwsdk.com/guides/database/drizzle Install the necessary Drizzle ORM and Drizzle Kit packages using npm. ```bash npm i drizzle-orm npm i -D drizzle-kit ``` -------------------------------- ### Install Ark UI with bun Source: https://docs.rwsdk.com/guides/frontend/ark-ui Use this command to add Ark UI React components to your project using bun. ```bash bun add @ark-ui/react ``` -------------------------------- ### Initialize shadcn/ui with yarn Source: https://docs.rwsdk.com/guides/frontend/shadcn Use this command with yarn to initialize shadcn/ui. It will guide you through theme selection and generate the `components.json` file. ```bash yarn dlx shadcn@latest init ``` -------------------------------- ### Install Vite TypeScript Paths Plugin with bun Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Install the `vite-tsconfig-paths` plugin using bun to synchronize TypeScript path configurations with Vite. ```bash bunx install -D vite-tsconfig-paths ``` -------------------------------- ### Run Development Server with yarn Source: https://docs.rwsdk.com/guides/frontend/ark-ui Command to start the development server using yarn. ```bash yarn run dev ``` -------------------------------- ### Accessing the Database Example Source: https://docs.rwsdk.com/guides/database/drizzle Example of how to query data from the 'users' table using the configured Drizzle instance in a React component. ```typescript // src/app/pages/dashboard.tsx import { db } from "@/db/db"; import { users, type User } from "@/db/schema"; export const Dashboard = async ({ ctx }: { ctx: any }) => { const allUsers: User[] = await db.select().from(users); } ``` -------------------------------- ### Local Email Output Example Source: https://docs.rwsdk.com/core/email This is an example of the console output when an email is sent locally. It indicates the binding call and the path to the generated .eml file. ```text send_email binding called with the following message: /var/folders/ft/8320mthj6gbdd2pmc42x13480000gn/T/miniflare-288e7109e15f898bd9877d7857386f8b/files/email/2dad29db-0a7d-498d-89ab-e961746835c4.eml ``` -------------------------------- ### Add all shadcn/ui components with yarn Source: https://docs.rwsdk.com/guides/frontend/shadcn Use yarn to add all shadcn/ui components. They will be installed in `src/app/components/ui`. ```bash yarn dlx shadcn@latest add ``` -------------------------------- ### Layout Nesting Order Example Source: https://docs.rwsdk.com/guides/frontend/layouts Illustrates how nested layouts are applied, with outer layouts wrapping inner ones. The example shows the resulting component hierarchy. ```plaintext layout(Outer, [layout(Inner, [route("/", Page)])]) // Results in: ``` -------------------------------- ### Install Tailwind CSS with Vite Source: https://docs.rwsdk.com/guides/frontend/tailwind Use these commands to install Tailwind CSS and its Vite plugin depending on your preferred package manager. ```bash npm install tailwindcss @tailwindcss/vite ``` ```bash yarn add tailwindcss @tailwindcss/vite ``` ```bash pnpm add tailwindcss @tailwindcss/vite ``` ```bash bun add tailwindcss @tailwindcss/vite ``` -------------------------------- ### Install Vite TypeScript Paths Plugin with npm Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Install the `vite-tsconfig-paths` plugin using npm to synchronize TypeScript path configurations with Vite. ```bash npx install -D vite-tsconfig-paths ``` -------------------------------- ### Install Ark UI with npm Source: https://docs.rwsdk.com/guides/frontend/ark-ui Use this command to add Ark UI React components to your project using npm. ```bash npm install @ark-ui/react ``` -------------------------------- ### Install Vite TypeScript Paths Plugin with pnpm Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Install the `vite-tsconfig-paths` plugin using pnpm to synchronize TypeScript path configurations with Vite. ```bash pnpx install -D vite-tsconfig-paths ``` -------------------------------- ### Install Ark UI with yarn Source: https://docs.rwsdk.com/guides/frontend/ark-ui Use this command to add Ark UI React components to your project using yarn. ```bash yarn add @ark-ui/react ``` -------------------------------- ### Run the Development Server Source: https://docs.rwsdk.com/getting-started/quick-start Start the development server to see your application in action. RedwoodSDK uses Vite for its development server. ```bash npm run dev ``` ```bash yarn run dev ``` ```bash pnpm run dev ``` ```bash bun run dev ``` -------------------------------- ### Install React Compiler Dependencies Source: https://docs.rwsdk.com/guides/optimize/react-compiler Install the React Compiler Babel plugin and Vite's React plugin. Ensure you are using the latest versions of React and related packages. ```bash pnpm add react@latest react-dom@latest react-server-dom-webpack@latest pnpm add -D babel-plugin-react-compiler@latest @vitejs/plugin-react@latest ``` -------------------------------- ### Install Ark UI with pnpm Source: https://docs.rwsdk.com/guides/frontend/ark-ui Use this command to add Ark UI React components to your project using pnpm. ```bash pnpm add @ark-ui/react ``` -------------------------------- ### Example Worker with Email Sending and Receiving Source: https://docs.rwsdk.com/core/email This TypeScript example demonstrates sending an email using `env.EMAIL.send()` and handling inbound emails by implementing the `email` handler. Ensure recipient addresses are verified in Cloudflare Email Routing for production. ```typescript import * as PostalMime from "postal-mime"; import { EmailMessage } from "cloudflare:email"; import { createMimeMessage } from "mimetext"; import { render, route } from "rwsdk/router"; import { defineApp } from "rwsdk/worker"; import { Document } from "@/app/Document"; import { setCommonHeaders } from "@/app/headers"; import { env, WorkerEntrypoint } from "cloudflare:workers"; const app = defineApp([ setCommonHeaders(), /** * This route is used to send an email from the worker * First, we create a MIME message with the sender, recipient, * and the content of the email. * Then, we create a new EmailMessage object with the * sender, recipient, and the raw content of the email. * Finally, we send the email using the `env.EMAIL.send()` method. * Ensure the `recipient@example.com` address is verified in Cloudflare Email Routing, or adjust the binding configuration accordingly. */ route("/email", async () => { const msg = createMimeMessage(); msg.setSender({ name: "Sending email test", addr: "sender@example.com" }); msg.setRecipient("recipient@example.com"); msg.setSubject("An email generated in a worker"); msg.addMessage({ contentType: "text/plain", data: `Congratulations, you just sent an email from a worker.`, }); const message = new EmailMessage( "sender@example.com", "recipient@example.com", msg.asRaw() ); await env.EMAIL.send(message); return Response.json({ ok: true }); }), ]); /** * This is the default worker entrypoint for the Worker. * It extends the WorkerEntrypoint class and implements the email and fetch handlers. */ // It extends the WorkerEntrypoint class and implements the email and fetch handlers. export default class DefaultWorker extends WorkerEntrypoint { /** * Email handler for the Worker. * The `message` parameter is an ForwardableEmailMessage object * * You can call `message.reply()` to respond directly to the * inbound sender without additional verification steps. */ async email(message: ForwardableEmailMessage) { const parser = new PostalMime.default(); const rawEmail = new Response((message as any).raw); const email = await parser.parse(await rawEmail.arrayBuffer()); console.log(email); } /** * Fetch handler for the Worker. * Needed so that the worker can handle the request and pass it to the app. */ override async fetch(request: Request) { return await app.fetch(request, this.env, this.ctx); } } ``` -------------------------------- ### Add a single shadcn/ui component with npm Source: https://docs.rwsdk.com/guides/frontend/shadcn Install a specific shadcn/ui component by name using npm. The component will be added to `src/app/components/ui`. ```bash npx shadcn@latest add ``` -------------------------------- ### Add a single shadcn/ui component with bun Source: https://docs.rwsdk.com/guides/frontend/shadcn Add a specific shadcn/ui component using bun. Components are installed in `src/app/components/ui`. ```bash bunx shadcn@latest add ``` -------------------------------- ### Client Component Example Source: https://docs.rwsdk.com/core/react-server-components A React Client Component marked with 'use client' for client-side interactivity. ```APIDOC ## Client Component Example ### Description A React Client Component marked with 'use client' for client-side interactivity. This component will be hydrated by React in the browser. ### Code ```javascript "use client"; export default function MyClientComponent() { return ; } ``` ``` -------------------------------- ### Fetching Data in Server Components Source: https://docs.rwsdk.com/core/react-server-components Example of fetching data within a server component and displaying it, with Suspense for loading states. ```APIDOC ## Fetching and displaying data ### Description React Server Components run on the server and can easily fetch data. This example shows how to fetch todos and display them, using Suspense for a loading state. ### Server Component Code ```javascript // src/app/pages/todos/TodoPage.tsx import { Suspense } from 'react'; export async function Todos({ ctx }) { const todos = await db.todo.findMany({ where: { userId: ctx.user.id } }); return (
    {todos.map((todo) => (
  1. {todo.title}
  2. ))}
); } export async function TodoPage({ ctx }) { return (

Todos

Loading...
}> ); } ``` ``` -------------------------------- ### Server Component Example Source: https://docs.rwsdk.com/core/react-server-components A basic React Server Component that renders static content on the server. ```APIDOC ## Server Component Example ### Description A basic React Server Component that renders static content on the server. ### Code ```javascript export default function MyServerComponent() { return
Hello, from the server!
; } ``` ``` -------------------------------- ### Complex Layout Composition Examples Source: https://docs.rwsdk.com/guides/frontend/layouts Demonstrates various valid ways to compose layouts with other router functions like `prefix`, `render`, and `routes`. ```typescript prefix("/api", layout(ApiLayout, routes)) // ✅ layout(AppLayout, prefix("/admin", routes)) // ✅ render(Document, layout(AppLayout, routes)) // ✅ ``` -------------------------------- ### Initialize shadcn/ui with bun Source: https://docs.rwsdk.com/guides/frontend/shadcn Initialize shadcn/ui with bun. Follow the prompts for theme selection, and a `components.json` file will be created. ```bash bunx shadcn@latest init ``` -------------------------------- ### Initialize shadcn/ui with npm Source: https://docs.rwsdk.com/guides/frontend/shadcn Run this command to initialize shadcn/ui in your project. It will prompt for theme selection and create a `components.json` configuration file. ```bash npx shadcn@latest init ``` -------------------------------- ### Integrating Theme Toggle in a Page Source: https://docs.rwsdk.com/guides/frontend/dark-mode This example shows how to import and use the `ThemeToggle` component within a page. It retrieves the initial theme from the context and passes it to the toggle component. ```tsx import { RequestInfo } from "rwsdk/worker"; import { ThemeToggle } from "../components/ThemeToggle"; export function Home({ ctx }: RequestInfo) { const theme = ctx.theme || "system"; return (

Welcome

); } ``` -------------------------------- ### Use Route-Specific Middleware with Method Handlers Source: https://docs.rwsdk.com/reference/sdk-router Method handlers can be arrays of functions, enabling the use of route-specific middleware. This example shows middleware for authentication and validation before handling GET and POST requests. ```typescript route("/api/users", { get: [isAuthenticated, getUsersHandler], post: [isAuthenticated, validateUser, createUserHandler], }); ``` -------------------------------- ### Explicitly Define HEAD Request Handler Source: https://docs.rwsdk.com/reference/sdk-router RedwoodSDK does not automatically map HEAD requests to GET handlers. You must explicitly define a `head` handler if you need to support HEAD requests, as shown in this example. ```typescript route("/api/users", { get: getHandler, head: getHandler, // Explicitly provide HEAD handler }); ``` -------------------------------- ### Initialize shadcn/ui with pnpm Source: https://docs.rwsdk.com/guides/frontend/shadcn Initialize shadcn/ui using pnpm. This command will handle theme selection and create the necessary `components.json` configuration. ```bash pnpx shadcn@latest init ``` -------------------------------- ### Local Testing Command Source: https://docs.rwsdk.com/core/email Use this command to start the local development server for testing email sending functionality. Access http://localhost:5173/email to trigger an email and view logs. ```bash pnpm dev ``` -------------------------------- ### Define a Basic Route Source: https://docs.rwsdk.com/reference/sdk-router Use the `route` function to define a handler for a specific path. This example sets up a handler for the root path that returns a simple 'Hello, World!' response. ```typescript import { route } from "rwsdk/router"; route("/", () => new Response("Hello, World!")); ``` -------------------------------- ### Create Project from Latest Pre-release Source: https://docs.rwsdk.com/reference/create-rwsdk To use the latest pre-release version (e.g., alpha, beta, rc) for your new project, include the --pre flag. ```bash npx create-rwsdk my-awesome-app --pre ``` -------------------------------- ### Test Chakra UI Components Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Use basic Chakra UI components like `Button`, `HStack`, and `Heading` in your application pages (e.g., `src/app/pages/Home.tsx`) to verify the installation and configuration. ```typescript import { Button, HStack, Heading } from "@chakra-ui/react"; export function Home() { return (
Welcome to Chakra UI v3
); } ``` -------------------------------- ### Add all shadcn/ui components with npm Source: https://docs.rwsdk.com/guides/frontend/shadcn Run this command to add all available shadcn/ui components to your project. Components will be placed in the `src/app/components/ui` folder. ```bash npx shadcn@latest add ``` -------------------------------- ### Create Project from Specific Release Version Source: https://docs.rwsdk.com/reference/create-rwsdk Specify a particular release version for your project using the --release flag followed by the version string. ```bash npx create-rwsdk my-awesome-app --release v1.0.0-alpha.10 ``` -------------------------------- ### Install workers-og Package Source: https://docs.rwsdk.com/guides/frontend/og-images Install the workers-og package to enable dynamic OG image generation using Cloudflare Workers. ```bash pnpm install workers-og ``` -------------------------------- ### Register State Set and Get Handlers Source: https://docs.rwsdk.com/experimental/realtime Register handlers for `set` and `get` operations to persist state to a database or load it when needed. ```typescript SyncedStateServer.registerSetStateHandler((key, value) => { console.log("State updated:", key, value); // db.save(key, value); }); SyncedStateServer.registerGetStateHandler((key, value) => { // potentially load from DB if value is undefined }); ``` -------------------------------- ### Install Vite TypeScript Paths Plugin with yarn Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Install the `vite-tsconfig-paths` plugin using yarn to synchronize TypeScript path configurations with Vite. ```bash yarn dlx install -D vite-tsconfig-paths ``` -------------------------------- ### Create a New RedwoodSDK Project Source: https://docs.rwsdk.com/reference/create-rwsdk Use this command to initialize a new RedwoodSDK project with a specified name. If no name is provided, the tool will prompt for it. ```bash npx create-rwsdk my-project ``` ```bash npx create-rwsdk my-awesome-app ``` ```bash npx create-rwsdk # You will be prompted: What is the name of your project? ``` -------------------------------- ### Set Up Resend API Key Source: https://docs.rwsdk.com/guides/email/sending-email Add your Resend API key to your .env file. Ensure you have a .env file; if not, duplicate .env.example and rename it. ```env RESEND_API=re_1234567890 ``` -------------------------------- ### Initialize Client with Navigation Handling Source: https://docs.rwsdk.com/reference/sdk-client Initializes the React Client and sets up client-side navigation handling by passing a custom `handleResponse` function obtained from `initClientNavigation`. ```javascript import { initClient, initClientNavigation } from "rwsdk/client"; const { handleResponse } = initClientNavigation(); initClient({ handleResponse }); ``` -------------------------------- ### Add all shadcn/ui components with bun Source: https://docs.rwsdk.com/guides/frontend/shadcn Add all shadcn/ui components using bun. Components are placed in `src/app/components/ui`. ```bash bunx shadcn@latest add ``` -------------------------------- ### Explicitly Handle HEAD Requests Source: https://docs.rwsdk.com/core/routing Unlike some frameworks, HEAD handlers must be explicitly provided and are not automatically mapped from GET handlers. You can reuse the GET handler if desired. ```javascript route("/api/users", { get: getHandler, head: getHandler, // Explicitly reuse handler }); ``` -------------------------------- ### Deploy to Production with bun Source: https://docs.rwsdk.com/core/hosting Use this command to deploy your web application to production using bun. You will be prompted to confirm the deployment. ```bash bun run release ``` -------------------------------- ### Deploy to Production with npm Source: https://docs.rwsdk.com/core/hosting Use this command to deploy your web application to production using npm. You will be prompted to confirm the deployment. ```bash npm run release ``` -------------------------------- ### Add Passkey Addon Source: https://docs.rwsdk.com/experimental/authentication Run this command to add the Passkey addon to your project. After execution, follow the instructions in the generated INSTRUCTIONS.md file for integration. ```bash npx rwsdk addon passkey ``` -------------------------------- ### HEAD Requests Source: https://docs.rwsdk.com/reference/sdk-router Explicitly defines HEAD handlers, as they are not automatically mapped from GET handlers. ```APIDOC ## `route` - HEAD Requests ### Description Explicitly define a HEAD handler if you want to support HEAD requests, as RedwoodSDK does not automatically map HEAD requests to GET handlers. ### Request Example ```javascript route("/api/users", { get: getHandler, head: getHandler, // Explicitly provide HEAD handler }); ``` ``` -------------------------------- ### Server Function Example Source: https://docs.rwsdk.com/core/react-server-components A server function that can be called from a client component to perform server-side operations. ```APIDOC ## Server Functions ### Description Server Functions allow you to execute code on the server from a client component. This example shows an `addTodo` function that creates a new todo item. ### Server Function Code ```javascript // @/pages/todos/functions.tsx "use server"; import { requestInfo } from "rwsdk/worker"; export async function addTodo(formData: FormData) { const { ctx } = requestInfo; const title = formData.get("title"); await db.todo.create({ data: { title, userId: ctx.user.id } }); } ``` ### Client Component Usage Example ```javascript // @/pages/todos/AddTodo.tsx "use client"; import { addTodo } from "./functions"; export default function AddTodo() { return (
); } ``` ``` -------------------------------- ### Initialize Client Navigation (Smooth Scroll) Source: https://docs.rwsdk.com/reference/sdk-client Initializes client navigation with smooth scrolling enabled for a more fluid user experience. ```javascript initClientNavigation({ scrollBehavior: "smooth", }); ``` -------------------------------- ### Create Database Instance Source: https://docs.rwsdk.com/experimental/database Create a typed database instance using `createDb()`. This involves providing the environment variable for the database, a unique key for the instance, and the migration types. ```typescript import { env } from "cloudflare:workers"; import { type Database, createDb } from "rwsdk/db"; import { type migrations } from "@/db/migrations"; export type AppDatabase = Database; export type Todo = AppDatabase["todos"]; export const db = createDb( env.DATABASE, "todo-database", // unique key for this database instance ); ``` -------------------------------- ### Define Initial App Structure Source: https://docs.rwsdk.com/getting-started/quick-start This is the entry point for your web application, defining how requests are handled and responses are generated. ```typescript import { defineApp } from "rwsdk/worker"; import { route, render } from "rwsdk/router"; import { Document } from "@/app/document"; import { Home } from "@/app/pages/home"; export default defineApp([ render(Document, [route("/", () => new Response("Hello, World!"))]), ]); ``` -------------------------------- ### Deploy to Production with pnpm Source: https://docs.rwsdk.com/core/hosting Use this command to deploy your web application to production using pnpm. You will be prompted to confirm the deployment. ```bash pnpm run release ``` -------------------------------- ### Create Custom System Configuration Source: https://docs.rwsdk.com/guides/frontend/chakra-ui Define custom color and font tokens, and semantic color tokens for your theme. This configuration is then passed to `createSystem`. ```typescript import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"; const customConfig = defineConfig({ theme: { tokens: { colors: { brand: { 50: { value: "#e6f7ff" }, 100: { value: "#bae7ff" }, 200: { value: "#91d5ff" }, 300: { value: "#69c0ff" }, 400: { value: "#40a9ff" }, 500: { value: "#1890ff" }, 600: { value: "#096dd9" }, 700: { value: "#0050b3" }, 800: { value: "#003a8c" }, 900: { value: "#002766" }, }, }, fonts: { heading: { value: "'Inter', sans-serif" }, body: { value: "'Inter', sans-serif" }, }, }, semanticTokens: { colors: { "bg.primary": { value: { _light: "{colors.white}", _dark: "{colors.gray.900}" }, }, "text.primary": { value: { _light: "{colors.gray.900}", _dark: "{colors.gray.100}" }, }, }, }, }, }); export const system = createSystem(defaultConfig, customConfig); ``` -------------------------------- ### Add a single shadcn/ui component with yarn Source: https://docs.rwsdk.com/guides/frontend/shadcn Use yarn to add a specific shadcn/ui component. It will be installed in `src/app/components/ui`. ```bash yarn dlx shadcn@latest add ``` -------------------------------- ### Example: Uncaught error in lifecycle Source: https://docs.rwsdk.com/guides/frontend/error-handling Demonstrates an error thrown within a `useEffect` hook, which will trigger the `onUncaughtError` handler. ```javascript "use client"; import { useEffect } from "react"; export function Component() { useEffect(() => { // This error will trigger onUncaughtError throw new Error("Lifecycle error"); }, []); return
Component
; } ``` -------------------------------- ### Method-Based Routing Source: https://docs.rwsdk.com/reference/sdk-router Handles different HTTP methods (GET, POST, DELETE) on the same path using a MethodHandlers object. ```APIDOC ## `route` - Method-Based Routing ### Description Handles different HTTP methods on the same path using a `MethodHandlers` object. ### Method ```javascript route(path: string, handlers: MethodHandlers) ``` ### Parameters * **path** (string) - The URL path for the route. * **handlers** (MethodHandlers) - An object where keys are HTTP methods and values are `RouteHandler` functions or arrays of functions. ### MethodHandlers Type ```typescript type MethodHandlers = { delete?: RouteHandler; get?: RouteHandler; head?: RouteHandler; patch?: RouteHandler; post?: RouteHandler; put?: RouteHandler; config?: { disable405?: true; disableOptions?: true; }; custom?: { [method: string]: RouteHandler; }; }; ``` ### Request Example ```javascript route("/api/users", { get: () => new Response(JSON.stringify(users)), post: () => new Response("Created", { status: 201 }), delete: () => new Response("Deleted", { status: 204 }), }); ``` ### Middleware Example ```javascript route("/api/users", { get: [isAuthenticated, getUsersHandler], post: [isAuthenticated, validateUser, createUserHandler], }); ``` ### Custom Methods Example ```javascript route("/api/search", { custom: { report: () => new Response("Report data"), }, }); ``` ``` -------------------------------- ### Enable Verbose Logging for Development Source: https://docs.rwsdk.com/guides/troubleshooting Increase logging verbosity to get detailed information about scan failures during development. ```bash VERBOSE=1 pnpm dev ``` -------------------------------- ### Initialize Client Navigation (Default) Source: https://docs.rwsdk.com/reference/sdk-client Initializes the client navigation with default settings, causing an instant jump to the top of the page on navigation. ```javascript import { initClientNavigation } from "rwsdk/client"; initClientNavigation(); ``` -------------------------------- ### Deploy to Production with yarn Source: https://docs.rwsdk.com/core/hosting Use this command to deploy your web application to production using yarn. You will be prompted to confirm the deployment. ```bash yarn run release ``` -------------------------------- ### Add all shadcn/ui components with pnpm Source: https://docs.rwsdk.com/guides/frontend/shadcn Add all shadcn/ui components using pnpm. The components will be located in `src/app/components/ui`. ```bash pnpx shadcn@latest add ``` -------------------------------- ### Create a New RedwoodSDK Project Source: https://docs.rwsdk.com/getting-started/quick-start Use this command to create a new RedwoodSDK project. Replace `my-project-name` with your desired project name. ```bash npx create-rwsdk my-project-name ``` ```bash yarn dlx create-rwsdk my-project-name ``` ```bash pnpx create-rwsdk my-project-name ``` ```bash bunx create-rwsdk my-project-name ``` -------------------------------- ### Basic Setup: Configure error handlers Source: https://docs.rwsdk.com/guides/frontend/error-handling Configures both `onUncaughtError` and `onCaughtError` handlers via `hydrateRootOptions` to log errors to the console. ```typescript initClient({ hydrateRootOptions: { onUncaughtError: (error, errorInfo) => { console.error("Uncaught error:", error); console.error("Component stack:", errorInfo.componentStack); }, onCaughtError: (error, errorInfo) => { console.error("Caught error:", error); console.error("Component stack:", errorInfo.componentStack); }, }, }); ``` -------------------------------- ### Create a Dynamic Welcome Email Template Source: https://docs.rwsdk.com/guides/email/email-templates Create a dynamic welcome email template by passing props to the component. This allows for personalized content. ```tsx interface WelcomeEmailProps { name: string; } export default function WelcomeEmail({ name }: WelcomeEmailProps) { return ( Hello {name} Hello {name} ); } ``` -------------------------------- ### Navigate After Form Submission Source: https://docs.rwsdk.com/guides/frontend/client-side-nav Use the `navigate` function to trigger navigation after a form submission. This example shows a basic redirect to the dashboard. ```javascript import { navigate } from "rwsdk/client"; function handleFormSubmit(event: FormEvent) { event.preventDefault(); navigate("/dashboard"); } ```