What You’ll Build
A Cloudflare Workers API with:- Text-to-image generation
- Video generation job management
- Hono’s lightweight routing
- TypeScript support
- Global edge deployment
Prerequisites
- Node.js 18 or higher
- A Cloudflare account
- A Decart API key
- Wrangler CLI
Setup
Start local development server
Complete Application Code
Deployment
API Usage
Generate Image
Generate Video (Async)
Submit job:Key Concepts
Hono Middleware
The middleware pattern creates a shared Decart client:c.get("decart").
TypeScript Types
Define types for environment bindings and context variables:Environment Variables
Access secrets viac.env:
Request/Response Handling
Hono provides clean request parsing and response building:Edge Benefits
Global Distribution
Cloudflare Workers run in 300+ locations worldwide, providing low latency for users anywhere.Zero Cold Starts
Workers have near-instant cold starts compared to traditional serverless functions.Cost Efficient
Pay only for requests, with generous free tier:- 100,000 requests/day free
- $0.50 per million requests after
Automatic Scaling
Handles traffic spikes without configuration.Wrangler Configuration
Thewrangler.toml file configures your worker:
wrangler.toml.
Local Development
For local development, use.dev.vars:
Error Handling
Add error handling for production:CORS Support
Enable CORS for frontend access:Production Best Practices
- Use Secrets - Always use
wrangler secretfor API keys - Add Rate Limiting - Implement rate limiting to prevent abuse
- Monitor Usage - Use Cloudflare Analytics to track usage
- Set Timeouts - Configure appropriate timeout limits
- Handle Errors - Return meaningful error messages
- Add Logging - Use
console.logfor debugging (visible in Wrangler tail)