### Start Local Development Server Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Starts a local development server with hot reload. Uses `.dev.vars` for configuration. ```bash npm run dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/README.md Install project dependencies using npm or pnpm. ```bash npm install # or pnpm install ``` -------------------------------- ### Copy Example Dev Vars Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Copies the example development variables file to a new file for local configuration. ```bash cp .dev.vars.example .dev.vars ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/README.md Copy the example environment variables file and add your Resend API key. ```bash cp .dev.vars.example .dev.vars # Edit .dev.vars and add your RESEND_API_KEY ``` -------------------------------- ### Install Resend Node.js SDK Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/README.md Install the Resend Node.js SDK using npm. This is the first step to integrate Resend into your project. ```bash npm install resend ``` -------------------------------- ### Install Dependencies Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Install project dependencies using your preferred package manager (pnpm, npm, or yarn). ```bash pnpm install ``` ```bash npm install ``` ```bash yarn install ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Command to install all project dependencies using pnpm. This is a common solution for 'Cannot find module' errors. ```bash pnpm install ``` -------------------------------- ### Run Locally Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/README.md Start the local development server for the Cloudflare Worker. ```bash npm run dev # Visit http://localhost:8787 ``` -------------------------------- ### Install and Configure Husky for Pre-Commit Hooks Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Install Husky to automate tasks like linting before each commit. This snippet shows the commands to install Husky and add a pre-commit hook for running npm run lint. ```bash npm install --save-dev husky npx husky install npx husky add .husky/pre-commit "npm run lint" ``` -------------------------------- ### .dev.vars.example file content Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/resend-sdk-integration.md An example file showing the structure for setting environment variables, specifically the RESEND_API_KEY, for local development. ```plaintext RESEND_API_KEY="" ``` -------------------------------- ### Custom Headers Response Example Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Demonstrates creating a response with custom headers, including 'Content-Type' and a custom 'X-Custom-Header'. ```typescript const headers = new Headers({ 'Content-Type': 'application/json', 'X-Custom-Header': 'value', }); return new Response(JSON.stringify(data), { status: 200, headers }); ``` -------------------------------- ### Access Bindings (KV, D1, R2) in TypeScript Code Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Demonstrates how to access configured bindings for KV, D1, and R2 services within your Worker's fetch handler using the `env` object. This code shows examples of getting data from KV, querying a D1 database, and uploading to an R2 bucket. ```typescript async fetch(request, env) { const cached = await env.CACHE.get('key'); // Get from KV const result = await env.DB.prepare('SELECT * FROM users').all(); // Query database await env.FILES.put('file.txt', 'content'); // Upload to R2 } ``` -------------------------------- ### Resend Email Sending Example Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md A complete example of sending an email using the Resend SDK, including handling success and error responses. ```typescript const data = await resend.emails.send({ from: 'noreply@company.com', to: ['user@example.com'], subject: 'Welcome!', react: , }); if (data.error) { console.error('Send failed:', data.error); } else { console.log('Sent:', data.id); } ``` -------------------------------- ### Set up Resend API Key for Development Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Commands to copy an example environment variables file and edit it to include your Resend API key. This is necessary for the application to authenticate with Resend. ```bash cp .dev.vars.example .dev.vars # Edit .dev.vars and add your API key ``` -------------------------------- ### fetch() Handler Implementation Example Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Demonstrates a typical fetch handler implementation that uses the Resend API to send an email. ```typescript export default { async fetch(request, env, context): Promise { const resend = new Resend(env.RESEND_API_KEY); const data = await resend.emails.send({ from: 'Acme ', to: ['delivered@resend.dev'], subject: 'hello world', react: , }); return Response.json(data); }, } satisfies ExportedHandler; ``` -------------------------------- ### Plain Text Response Example Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Demonstrates creating a simple plain text response with a 200 OK status. ```typescript return new Response('Hello, world!', { status: 200 }); ``` -------------------------------- ### NPM Scripts for Development Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md Common NPM scripts for managing the development environment, including starting the dev server and linting. ```bash npm run dev npm run lint npm run lint:fix ``` -------------------------------- ### Parsing Request Example Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Shows how to access properties of the Request object, such as method, URL, pathname, and search parameters, and how to parse the request body. ```typescript async fetch(request: Request, env: Env) { const method = request.method; // "GET", "POST", etc. const url = new URL(request.url); const pathname = url.pathname; // "/path" const searchParams = url.searchParams; // URLSearchParams if (request.method === 'POST') { const body = await request.json(); // Parse JSON body // process body } return new Response('OK', { status: 200 }); } ``` -------------------------------- ### Wrangler TOML Environment Overrides Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Example configuration for environment-specific overrides in `wrangler.toml`, including variables and routes for staging and production. ```toml [env.staging] vars = { ENVIRONMENT = "staging" } routes = [{ pattern = "staging.*", zone_name = "example.com" }] [env.production] vars = { ENVIRONMENT = "production" } routes = [{ pattern = "api.*", zone_name = "example.com" }] ``` -------------------------------- ### Error Response Example Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Shows how to construct an error response with a JSON body, a specific status code (400), and custom headers. ```typescript return Response.json( { error: 'Invalid email address' }, { status: 400, headers: { 'content-type': 'application/json' } } ); ``` -------------------------------- ### Automate Deployment with GitHub Actions Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/deployment-guide.md Set up a GitHub Actions workflow to automate the deployment of your Cloudflare Worker. This includes checking out code, setting up Node.js, installing dependencies, linting, and deploying using the Wrangler action. ```yaml name: Deploy on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 - run: npm install - run: npm run lint - uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} secrets: | RESEND_API_KEY env: RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} ``` -------------------------------- ### Environment-Specific Configuration Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Defines environment-specific variables. For example, setting the `ENVIRONMENT` variable for the production environment. ```toml [env.production] vars = { ENVIRONMENT = "prod" } ``` -------------------------------- ### Install and Update Dependencies with pnpm Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Commands for managing project dependencies using pnpm. Includes checking for outdated packages, updating all packages, and updating a specific package like Resend. ```bash pnpm outdated ``` ```bash pnpm update ``` ```bash pnpm add resend@latest ``` -------------------------------- ### Usage in Worker Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/email-template.md Example of how to import and use the EmailTemplate component within a Cloudflare Worker. ```typescript import { EmailTemplate } from './emails/email-template'; // ... in the fetch handler: react: ``` -------------------------------- ### Verify Worker Deployment Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/00-START-HERE.txt Example cURL command to test your deployed Cloudflare Worker. Replace placeholders with your actual deployment details. ```bash curl https://..workers.dev ``` -------------------------------- ### Implement Caching with Cache-Control Header Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Shows how to set the `Cache-Control` header in a Worker's response to leverage Cloudflare's global cache. This example caches the response for one hour. ```typescript return Response.json(data, { headers: { 'Cache-Control': 'max-age=3600', // Cache 1 hour }, }); ``` -------------------------------- ### Cloudflare Worker Handler Implementation Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md Example implementation of a Cloudflare Worker's fetch handler that sends an email using the Resend SDK. ```typescript const resend = new Resend(env.RESEND_API_KEY); const data = await resend.emails.send({ from: 'Acme ', to: ['delivered@resend.dev'], subject: 'hello world', react: , }); return Response.json(data); ``` -------------------------------- ### Cloudflare Worker Fetch Handler Implementation Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/types.md Provides an example of a Cloudflare Worker's fetch handler implementation, satisfying the ExportedHandler type with project-specific Env and ExecutionContext. ```typescript export default { async fetch(request, env, context): Promise { // handler implementation }, } satisfies ExportedHandler; ``` -------------------------------- ### Set Multiple Environment Variables in .dev.vars Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Example of how to define multiple environment variables within the `.dev.vars` file for local development. These variables can be accessed in your Worker code. ```dotenv RESEND_API_KEY=re_xxxxxxxxxxxxx DEBUG=true LOG_LEVEL=debug ``` -------------------------------- ### Configure Cron Trigger for Scheduled Tasks Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/deployment-guide.md Define cron schedules for triggering tasks. This example sets a daily trigger at noon UTC. ```toml [triggers] crons = ["0 12 * * *"] # Daily at noon UTC ``` -------------------------------- ### GitHub Actions CI/CD Pipeline for Cloudflare Workers Deployment Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md A GitHub Actions workflow to automatically deploy to Cloudflare Workers on push to the main branch. It includes installing dependencies, linting, and using the wrangler-action. ```yaml name: Deploy to Workers on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - run: npm install - run: npm run lint - uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} secrets: | RESEND_API_KEY env: RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }} ``` -------------------------------- ### Set RESEND_API_KEY in .dev.vars Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/resend-sdk-integration.md Example of how to set the Resend API key in the .dev.vars file for local development. This file is used by Cloudflare Workers to manage environment variables. ```bash RESEND_API_KEY=re_xxxxxxxxxxxxx ``` -------------------------------- ### Run Wrangler Dev Server on a Different Port Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Command to start the Wrangler development server on a port other than the default (8787). This is useful if the default port is already in use. ```bash wrangler dev --port 8788 ``` -------------------------------- ### Send Email using React Template Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/resend-sdk-integration.md Sends an email using the Resend SDK, specifying sender, recipient, subject, and a React component for the email body. This example uses a placeholder API key. ```typescript const data = await resend.emails.send({ from: 'Acme ', to: ['delivered@resend.dev'], subject: 'hello world', react: , }); ``` -------------------------------- ### Set Security Headers for Responses Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Example of setting important security headers like X-Frame-Options, X-Content-Type-Options, and Strict-Transport-Security in a Worker's response. These headers help protect against common web vulnerabilities. ```typescript const headers = new Headers({ 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains', }); return new Response(body, { headers }); ``` -------------------------------- ### Correct and Incorrect TypeScript Import Paths Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Illustrates the correct and incorrect ways to import modules in TypeScript within a Cloudflare Worker project. Ensure relative paths start with './' or '../' and include file extensions. ```typescript // Correct import { EmailTemplate } from './emails/email-template'; // Incorrect (missing ./ or extension) import { EmailTemplate } from 'emails/email-template'; ``` -------------------------------- ### Obtain Resend API Key Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Instructions to navigate to the Resend website, create an API key, and copy it for use in configuration. ```bash https://resend.com/api-keys ``` -------------------------------- ### Extending EmailTemplate with More Props Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/email-template.md Example of customizing the EmailTemplate to accept additional props like lastName and activationUrl. ```typescript interface EmailTemplateProps { firstName: string; lastName: string; activationUrl: string; } export function EmailTemplate({ firstName, lastName, activationUrl }: EmailTemplateProps) { return (

Welcome, {firstName} {lastName}!

Click here to activate your account.

); } ``` -------------------------------- ### Clone Repository Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Clone the project repository and navigate into the project directory. ```bash git clone https://github.com/resend/resend-cloudflare-workers-example.git cd resend-cloudflare-workers-example ``` -------------------------------- ### Instantiate Resend Client with Placeholder Key Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/resend-sdk-integration.md Initializes the Resend client using a placeholder API key. For production, this should be replaced with a key from environment variables. ```typescript const resend = new Resend('re_123456789' /* env.RESEND_API_KEY */); ``` -------------------------------- ### Resend SDK Initialization and Email Sending Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md Initializes the Resend SDK with an API key and demonstrates the basic structure for sending an email. ```typescript const resend = new Resend(apiKey: string); const result = await resend.emails.send(options: EmailOptions); ``` -------------------------------- ### Dynamic Content with Conditional Rendering Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/email-template.md Example of using conditional rendering within EmailTemplate based on props like isPremium. ```typescript interface EmailTemplateProps { firstName: string; isPremium: boolean; } export function EmailTemplate({ firstName, isPremium }: EmailTemplateProps) { return (

Welcome, {firstName}

{isPremium &&

You have premium access!

}
); } ``` -------------------------------- ### Define KV, D1, and R2 Bindings in wrangler.toml Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Illustrates how to configure bindings for KV Namespaces, D1 Databases, and R2 Buckets within your wrangler.toml file. These bindings allow your Worker to access these services. ```toml # KV Namespace [[kv_namespaces]] binding = "CACHE" id = "abc123..." # D1 Database [[d1_databases]] binding = "DB" database_name = "mydb" database_id = "xyz789..." # R2 Bucket [[r2_buckets]] binding = "FILES" bucket_name = "my-bucket" ``` -------------------------------- ### Instantiate Resend Client with Environment Variable Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/resend-sdk-integration.md Correctly instantiates the Resend client by retrieving the API key from the environment variables. This is the recommended approach for production. ```typescript const resend = new Resend(env.RESEND_API_KEY); ``` -------------------------------- ### fetch Method Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/worker-handler.md The `fetch` method is the primary entry point for handling incoming HTTP requests. It processes the request, instantiates the Resend client, sends an email using the provided template, and returns the email send result as a JSON response. ```APIDOC ## fetch(request: Request, env: Env, context: ExecutionContext): Promise ### Description Handles incoming HTTP requests, sends an email using the Resend service, and returns the result. ### Method POST (or GET, as per usage example) ### Endpoint `/` (Root of the deployed worker) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body This method does not explicitly define a request body. The email content is defined within the handler's code (e.g., `from`, `to`, `subject`, `react`). ### Request Example (Note: The request body is not directly used by this handler. The example below shows a typical invocation, but the handler's logic dictates the email content.) ```json { "message": "This is a placeholder, actual email content is defined in the worker code." } ``` ### Response #### Success Response (200) - **data** (object) - An object containing the result of the email send operation. Typically includes an `id` field. #### Response Example ```json { "id": "msg_abcdef1234567890" } ``` #### Error Response (500) - **error** (string) - A message describing the error that occurred during processing or email sending. ``` -------------------------------- ### Build Production Bundle for Cloudflare Workers Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Command to build the project for production. Note that for this specific project, Wrangler handles compilation during deployment, so this command might not perform a separate build step. ```bash npm run build ``` -------------------------------- ### Exhaustiveness Checking Example Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/types.md Demonstrates exhaustiveness checking for union types using `EmailResult`. TypeScript ensures all possible cases of the union are handled. ```typescript type EmailResult = | { success: true; id: string } | { success: false; error: string }; function handleResult(result: EmailResult) { if (result.success) { // TypeScript narrows to true case console.log(result.id); } else { // TypeScript narrows to false case console.log(result.error); } // All cases covered; no "else" needed } ``` -------------------------------- ### Deploy to Production Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/README.md Deploy the Cloudflare Worker to production by setting the Resend API key as a secret and then deploying. ```bash wrangler secret put RESEND_API_KEY wrangler deploy ``` -------------------------------- ### Create JSON Response with Response.json() Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md Example of creating a JSON response using the Response.json() method in Cloudflare Workers. This automatically sets the Content-Type header to application/json. ```typescript Response.json({ id: 'msg_123' }) ``` -------------------------------- ### Package JSON Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/00-START-HERE.txt Node.js project configuration. Lists dependencies, development scripts, and project metadata. ```json { "name": "resend-cloudflare-workers-example", "version": "0.1.0", "private": true, "scripts": { "dev": "wrangler dev", "start": "wrangler dev", "deploy": "wrangler deploy", "lint": "next lint", "lint:fix": "next lint --fix" }, "dependencies": { "react": "19.1.0", "react-dom": "19.1.0", "resend": "^6.0.1" }, "devDependencies": { "@cloudflare/workers-types": "^4.20240613.0", "@types/react": "18.3.3", "@types/react-dom": "18.3.0", "typescript": "^5.5.2", "wrangler": "^3.64.0" } } ``` -------------------------------- ### Configure Cron Trigger Schedule in wrangler.toml Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Defines a cron trigger in wrangler.toml to schedule the execution of your Worker. This example sets the cron to run daily at midnight UTC. ```toml [triggers] crons = ["0 0 * * *"] # Daily at midnight UTC ``` -------------------------------- ### Package.json Metadata and Scripts Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Defines project metadata, package manager, and scripts for development, linting, and fixing. ```json { "name": "resend-cloudflare-workers-example", "version": "0.0.0", "private": true, "packageManager": "pnpm@11.3.0", "scripts": { "dev": "wrangler dev", "lint": "biome check .", "lint:fix": "biome check . --write" } } ``` -------------------------------- ### TypeScript JSDoc for Email Sending Function Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Add JSDoc comments to TypeScript functions to generate type hints in editors. This example shows how to document a function that sends an email. ```typescript /** * Send an email using Resend. * @param env - Worker environment with RESEND_API_KEY * @returns Promise resolving to email send result */ async function sendEmail(env: Env): Promise<{ id?: string; error?: string }> { // implementation } ``` -------------------------------- ### Package.json Dependencies Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Lists production and development dependencies for the project, including React, Resend SDK, and development tools. ```json { "dependencies": { "react": "19.1.0", "react-dom": "19.1.0", "resend": "6.0.1" }, "devDependencies": { "@biomejs/biome": "2.2.0", "@cloudflare/workers-types": "4.20250821.0", "@types/react": "19.1.8", "@types/react-dom": "19.1.6", "typescript": "5.8.3", "wrangler": "4.31.0" } } ``` -------------------------------- ### Access Environment Variables in Worker Code Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Illustrates how to access environment variables, such as `DEBUG`, within your Cloudflare Worker TypeScript code. The example checks if debug mode is enabled. ```typescript if (env.DEBUG === 'true') { console.log('Debug mode enabled'); } ``` -------------------------------- ### Styling Emails with Inline Styles Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/email-template.md Demonstrates how to apply inline styles to the EmailTemplate for email client compatibility. ```typescript export function EmailTemplate({ firstName }: EmailTemplateProps) { return (

Welcome, {firstName}!

Thanks for signing up.

); } ``` -------------------------------- ### Import Resend SDK Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/resend-sdk-integration.md Imports the Resend class constructor from the resend package. This is the first step to using the SDK. ```typescript import { Resend } from 'resend'; ``` -------------------------------- ### JSON Response Constructor Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Illustrates how to create a JSON response using the Response.json() static method, including setting the status code. ```typescript const data = { id: 'msg_123', status: 'sent' }; return Response.json(data, { status: 200 }); ``` -------------------------------- ### Configure Multiple Environments in wrangler.toml Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/deployment-guide.md This TOML snippet defines environment-specific configurations for Cloudflare Workers, including different routes for staging and production. It demonstrates how to manage deployment targets within a single wrangler.toml file. ```toml [env.staging] route = "staging.example.com/email/*" [env.production] route = "api.example.com/email/*" ``` -------------------------------- ### Worker Entry Point Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Specifies the main entry point file for the Worker, relative to the project root. This file must export an `ExportedHandler`. ```toml main = "src/index.tsx" ``` -------------------------------- ### Implementing Path-Based Routing in Cloudflare Workers Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Manually route requests based on the URL pathname and HTTP method. This example shows how to handle different paths for sending data and health checks. ```typescript const url = new URL(request.url); const pathname = url.pathname; if (pathname === '/send' && request.method === 'POST') { // Handle send return Response.json({ id: 'msg_123' }); } else if (pathname === '/health') { // Handle health check return new Response('OK'); } else { return new Response('Not Found', { status: 404 }); } ``` -------------------------------- ### Sign Data with HMAC using Web Crypto API Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Demonstrates how to sign data using HMAC with the Web Crypto API. This is useful for creating signatures for URLs or other data to ensure integrity and authenticity. ```typescript const signature = crypto.subtle.sign( 'HMAC', key, new TextEncoder().encode(url) ); ``` -------------------------------- ### Login to Cloudflare Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/deployment-guide.md Authenticates your local environment with Cloudflare using the Wrangler CLI. This command opens a browser for authentication and stores credentials locally. ```bash wrangler login ``` -------------------------------- ### Generate AES-GCM Key for Web Crypto API Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Example of generating a new AES-GCM key using the Web Crypto API within a Cloudflare Worker. This key can be used for encryption and decryption operations. ```typescript const key = await crypto.subtle.generateKey( { name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'] ); ``` -------------------------------- ### Check Code Style Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Run the lint command to check code style and identify potential issues. ```bash npm run lint ``` -------------------------------- ### Log Messages with Different Levels in TypeScript Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Shows how to use console.log, console.warn, and console.error for different logging severities. These logs are visible during local development with `wrangler dev` and in real-time from production using `wrangler tail`. ```typescript console.log('Info message'); // General information console.warn('Warning message'); // Warning console.error('Error message'); // Error ``` -------------------------------- ### Resend API Key Format Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md Illustrates the expected format and prefix for Resend API keys. ```text Prefix: re_ Example: re_abc123def456ghi789 ``` -------------------------------- ### Handling HTTP Methods in Cloudflare Workers Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Use a switch statement to handle different HTTP methods (GET, POST, PUT, DELETE) within your Worker's fetch handler. Provide a default response for unsupported methods. ```typescript switch (request.method) { case 'GET': return handleGet(request); case 'POST': return handlePost(request); case 'PUT': return handlePut(request); case 'DELETE': return handleDelete(request); default: return new Response('Method Not Allowed', { status: 405 }); } ``` -------------------------------- ### Wrangler Commands for Deployment and Management Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md Essential Wrangler CLI commands for deploying, managing, and debugging Cloudflare Workers. ```bash wrangler deploy wrangler dev wrangler tail wrangler secret put KEY wrangler secret list wrangler delete ``` -------------------------------- ### Create JSON Response with Custom Headers Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md Demonstrates creating a JSON response with custom headers. This allows you to include additional information or control caching behavior. ```typescript Response.json(data, { status: 200, headers: { 'X-Custom-Header': 'value', 'Cache-Control': 'no-cache', }, }) ``` -------------------------------- ### Deploy Worker to Staging Environment Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/deployment-guide.md This bash command deploys the Cloudflare Worker to the staging environment as defined in the wrangler.toml file. Use this for testing before deploying to production. ```bash wrangler deploy --env staging ``` -------------------------------- ### Deploy Worker Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/00-START-HERE.txt Command to deploy your Cloudflare Worker to the specified environment. ```bash wrangler deploy ``` -------------------------------- ### Resend Class Constructor Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/types.md Illustrates the constructor for the Resend API client, requiring an API key for initialization. ```typescript class Resend { constructor(apiKey: string); emails: EmailsAPI; } ``` -------------------------------- ### Dynamic Recipients from Query Parameters Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md This code snippet shows how to dynamically set email recipients based on a 'email' query parameter in the request URL. If no parameter is provided, it defaults to 'default@example.com'. ```typescript const url = new URL(request.url); const recipient = url.searchParams.get('email') || 'default@example.com'; const data = await resend.emails.send({ from: 'noreply@example.com', to: [recipient], subject: 'Hello', react: , }); ``` -------------------------------- ### Automated Email Testing with Vitest Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md This snippet demonstrates how to set up automated tests for email templates using Vitest. It ensures that the `EmailTemplate` component renders correctly with provided props and includes expected content. ```typescript import { describe, it, expect } from 'vitest'; import { EmailTemplate } from '../src/emails/email-template'; import { render } from '@react-email/render'; describe('EmailTemplate', () => { it('renders with firstName prop', () => { const html = render(); expect(html).toContain('Jane'); expect(html).toContain('Welcome'); }); }); ``` -------------------------------- ### Importing EmailTemplate Component Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/email-template.md Shows the two common import methods for the EmailTemplate component. ```typescript // Named import import { EmailTemplate } from './emails/email-template'; // Default import import EmailTemplate from './emails/email-template'; ``` -------------------------------- ### Enable Node.js Compatibility Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Enables Node.js-compatible APIs, such as `Buffer` and `process`, which are required by the Resend SDK and React. ```toml compatibility_flags = ["nodejs_compat"] ``` -------------------------------- ### Deploy Worker to Production Environment Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/deployment-guide.md This bash command deploys the Cloudflare Worker to the production environment as defined in the wrangler.toml file. Ensure all configurations and tests are complete before running this command. ```bash wrangler deploy --env production ``` -------------------------------- ### Worker Lifecycle Flowchart Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/cloudflare-workers-reference.md Illustrates the sequence of events from a client request to a client response when processed by a Cloudflare Worker. ```text Client Request ↓ Cloudflare Edge Server ↓ Execute fetch() handler ↓ Return Response ↓ Client Response ``` -------------------------------- ### Biome Linter Configuration Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/configuration.md Minimal Biome linter configuration, typically inheriting defaults. Custom rules can be added to extend its functionality. ```json { "linter": { "enabled": true, "rules": { "suspicious": { "noExplicitAny": "error" }, "style": { "useNamingConvention": "warn" } } } } ``` -------------------------------- ### Adding a New Component Export Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/module-exports.md To add a new component, define it in a new file and export it. Then, import it into the main entry point (`src/index.tsx`). ```typescript // src/emails/footer.tsx export function Footer() { return
...
; } ``` ```typescript // src/index.tsx import { Footer } from './emails/footer'; ``` -------------------------------- ### Find and Kill Process Using a Port (macOS/Linux) Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Shell commands to identify and terminate a process that is occupying a specific network port. Useful for resolving port conflicts. ```bash # macOS/Linux lsof -i :8787 kill -9 ``` -------------------------------- ### Stage and Commit Changes in Git Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Commands to stage specific files and commit them with a descriptive message. This is a standard step in the Git version control process. ```bash git add src/index.tsx src/emails/email-template.tsx git commit -m "Add support for email attachments" ``` -------------------------------- ### Create JSON Response with Status Code Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md Shows how to create a JSON response with a specified HTTP status code using Response.json(). This is useful for indicating success or failure. ```typescript Response.json({ error: 'Invalid email' }, { status: 400 }) ``` -------------------------------- ### Create Email Template with React Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/README.md Define a React component for your email template. This allows for dynamic content generation using props. ```tsx import * as React from 'react'; interface EmailTemplateProps { firstName: string; } export const EmailTemplate: React.FC> = ({ firstName, }) => (

Welcome, {firstName}!

); export default EmailTemplate; ``` -------------------------------- ### Find and Kill Process Using a Port (Windows) Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/development-guide.md Command prompt commands to find the Process ID (PID) using a specific port and then terminate that process. Helps in resolving port conflicts on Windows. ```bash # Windows netstat -ano | findstr :8787 taskkill /PID /F ``` -------------------------------- ### Cloudflare Worker Fetch Handler Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/project-overview.md The main entry point for the Cloudflare Worker. It handles incoming requests, initializes the Resend client, and sends an email. ```typescript import { Resend } from "resend"; import { EmailTemplate } from "./emails/email-template"; // Define environment variable types interface Env { RESEND_API_KEY: string; } export const onRequest: ExportedHandler = { async fetch(request, env, context) { const resend = new Resend(env.RESEND_API_KEY); try { const data = await resend.emails.send({ from: "Acme ", to: ["delivered@resend.dev"], subject: "Hello from Cloudflare Workers!", react: EmailTemplate({ name: "User" }), }); return new Response(JSON.stringify(data), { headers: { "content-type": "application/json", }, }); } catch (error) { console.error(error); return new Response(JSON.stringify({ error }), { status: 500, headers: { "content-type": "application/json", }, }); } }, }; export default {}; ``` -------------------------------- ### Worker Entry Point Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/00-START-HERE.txt The default exported handler for Cloudflare Workers. It implements the `fetch` method to process incoming requests. ```typescript export default exportedHandler; interface Env { // Example binding for a durable object // MY_DURABLE_OBJECT: DurableObjectNamespace, // Example binding for secrets RESEND_API_KEY: string; } const exportedHandler: ExportedHandler = { async fetch(request, env, context) { const url = new URL(request.url); const resend = new Resend(env.RESEND_API_KEY); if (url.pathname === "/") { try { const email = await resend.emails.send({ from: "Acme ", to: "delivered@resend.com", subject: "Hello World", html: "

Congrats on sending your first email!

", }); return new Response(JSON.stringify(email), { headers: { "Content-Type": "application/json", }, }); } catch (error) { return new Response(JSON.stringify({ error }), { status: 500, headers: { "Content-Type": "application/json", }, }); } } return new Response("Not Found", { status: 404, }); }, }; ``` -------------------------------- ### npm Scripts Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/README.md Common npm scripts for managing the development environment, linting, and auto-fixing code issues. ```bash npm run dev # Start local development server npm run lint # Check code with linter npm run lint:fix # Auto-fix code issues ``` -------------------------------- ### Env Interface Usage in Fetch Handler Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/types.md Demonstrates how to access the RESEND_API_KEY from the environment bindings within a Cloudflare Worker's fetch handler. ```typescript async fetch(request, env, context) { const resend = new Resend(env.RESEND_API_KEY); // ... } ``` -------------------------------- ### Worker Handler Source: https://github.com/resend/resend-cloudflare-workers-example/blob/main/_autodocs/api-quick-reference.md The main entry point for the Cloudflare Worker. It receives incoming requests and environment bindings, uses the Resend API key to initialize the Resend client, and sends an email using the provided options. ```APIDOC ## Worker Handler ### Description Handles incoming requests for the Cloudflare Worker. It initializes the Resend client using the `RESEND_API_KEY` from the environment and sends an email. ### Method `fetch(request: Request, env: Env, context: ExecutionContext)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (handled by the `Request` object) ### Handler Signature ```typescript async fetch(request: Request, env: Env, context: ExecutionContext): Promise ``` ### Environment Variables - `RESEND_API_KEY` (string): Your Resend API key. ### Returns `Promise`: A response object containing the result of the email send operation. ### Example Implementation ```typescript const resend = new Resend(env.RESEND_API_KEY); const data = await resend.emails.send({ from: 'Acme ', to: ['delivered@resend.dev'], subject: 'hello world', react: , }); return Response.json(data); ``` ```