Trong bài viết này, chúng ta sẽ cùng tìm hiểu cách xây dựng một ứng dụng serverless hoàn chỉnh sử dụng TypeScript, Cloudflare Workers, và D1 Database.
🚀 Tại sao chọn Cloudflare Workers?
Cloudflare Workers là nền tảng serverless hiện đại mang lại nhiều lợi ích vượt trội:
1. Hiệu suất đỉnh cao
- Latency thấp: Code chạy tại 275+ datacenter toàn cầu
- Cold start ~0ms: Nhanh hơn nhiều so với AWS Lambda
- Edge computing: Xử lý gần người dùng nhất
2. Chi phí tối ưu
- Free tier: 100,000 requests/ngày
- Paid plan: Chỉ $5/tháng cho 10 triệu requests
- Không tính theo thời gian chạy: Tiết kiệm đáng kể
3. Developer Experience tuyệt vời
- TypeScript support native
- Local development với Wrangler
- Hot reload cực nhanh
- Debugging dễ dàng
📦 Stack công nghệ
Dự án sử dụng các công nghệ sau:
{
"runtime": "Cloudflare Workers",
"database": "D1 (SQLite)",
"orm": "Drizzle ORM",
"framework": "Hono",
"language": "TypeScript 5.4",
"deployment": "Wrangler CLI"
}
🏗️ Kiến trúc hệ thống
┌─────────────┐
│ Client │
└──────┬──────┘
│
▼
┌─────────────────────┐
│ Cloudflare Edge │
│ (275+ locations) │
└──────┬──────────────┘
│
▼
┌─────────────────────┐
│ Workers (Hono) │
│ ├─ Routes │
│ ├─ Controllers │
│ └─ Services │
└──────┬──────────────┘
│
├──────┬──────────┐
│ │ │
▼ ▼ ▼
┌────┐ ┌────┐ ┌─────────┐
│ D1 │ │ KV │ │WordPress│
└────┘ └────┘ └─────────┘
💻 Code Examples
1. Khởi tạo Hono App
import { Hono } from "hono";
import { cors } from "hono/cors";
const app = new Hono<{ Bindings: Env }>();
// Middleware
app.use("*", cors());
// Routes
app.get("/api/posts", async (c) => {
const db = drizzle(c.env.DB);
const posts = await db.select().from(postsTable);
return c.json(posts);
});
export default app;
2. Drizzle ORM Schema
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
export const posts = sqliteTable("posts", {
id: integer("id").primaryKey({ autoIncrement: true }),
title: text("title").notNull(),
content: text("content").notNull(),
status: text("status", {
enum: ["draft", "published"],
}).default("draft"),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(
() => new Date()
),
});
3. WordPress REST API Integration
async function publishToWordPress(post: Post, env: Env) {
const auth = btoa(`${env.WP_USER}:${env.WP_PASSWORD}`);
const response = await fetch(`${env.WP_SITE_URL}/wp-json/wp/v2/posts`, {
method: "POST",
headers: {
Authorization: `Basic ${auth}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
title: post.title,
content: post.content,
status: "publish",
}),
});
return await response.json();
}
📊 Performance Benchmarks
| Metric | Cloudflare Workers | AWS Lambda | Vercel Edge |
|---|---|---|---|
| Cold Start | ~0ms | ~200ms | ~50ms |
| Global Locations | 275+ | 25+ | 100+ |
| Free Tier | 100K/day | 1M/month | 100GB-hours |
| Pricing (10M) | $5 | $20 | $40 |
🛠️ Best Practices
1. Type Safety
Luôn sử dụng TypeScript strict mode:
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitReturns": true
}
}
2. Error Handling
Implement proper error handling:
app.onError((err, c) => {
console.error("Error:", err);
return c.json(
{
error: "Internal Server Error",
message: err.message,
},
500
);
});
3. Environment Variables
Sử dụng Wrangler Secrets cho production:
# Local: .dev.vars
WORDPRESS_SITE_URL=https://example.com
# Production
wrangler secret put WORDPRESS_SITE_URL
4. Database Optimization
Tạo indexes cho queries thường dùng:
CREATE INDEX idx_posts_status ON posts(status);
CREATE INDEX idx_posts_created_at ON posts(created_at);
🎯 Use Cases
1. CMS Headless
- WordPress làm backend
- Cloudflare Workers làm API layer
- JAMstack frontend (Next.js, Astro)
2. API Gateway
- Route requests từ multiple sources
- Transform data
- Cache với Cache API
3. Webhook Handler
- Nhận webhooks từ services
- Process data
- Store vào D1 hoặc forward đi
4. Scheduled Tasks
- Cron jobs với Workers
- Data sync
- Automated publishing
📈 Scaling Strategy
Phase 1: Free Tier (0-100K requests/day)
- Single Worker
- D1 Database
- Basic caching
Phase 2: Paid Tier (100K-10M requests/day)
- Multiple Workers
- KV for caching
- Durable Objects for coordination
Phase 3: Enterprise (10M+ requests/day)
- Load balancing
- Multiple regions
- Advanced monitoring
🔒 Security Checklist
- ✅ Sử dụng HTTPS only
- ✅ Rate limiting với KV
- ✅ Input validation
- ✅ CORS configuration
- ✅ Secrets management
- ✅ API authentication
- ✅ SQL injection prevention (ORM)
- ✅ XSS protection
🚀 Deployment
Development
npm run dev
Production
# Deploy
npm run deploy
# Rollback
wrangler rollback
📚 Resources
Official Documentation
Community
💡 Tips & Tricks
1. Local Development
# Sử dụng .dev.vars cho local env
cp .env.example .dev.vars
# Run với watch mode
wrangler dev --local
2. Testing
# Unit tests
npm run test
# Integration tests
npm run test:integration
3. Monitoring
# Tail logs real-time
wrangler tail
# View metrics
wrangler metrics
🎓 Learning Path
-
Week 1: Basics
- TypeScript fundamentals
- Cloudflare Workers concepts
- Hono framework
-
Week 2: Database
- D1 Database
- Drizzle ORM
- Migrations
-
Week 3: Integration
- REST API design
- WordPress integration
- Authentication
-
Week 4: Production
- Deployment
- Monitoring
- Optimization
🎯 Kết luận
Cloudflare Workers kết hợp với TypeScript tạo nên một stack công nghệ mạnh mẽ cho:
✨ Hiệu suất cao – Edge computing với latency thấp
✨ Chi phí thấp – Free tier rộng rãi
✨ Developer Experience – Type safety và tooling tốt
✨ Scalability – Scale globally tự động
Bắt đầu dự án của bạn ngay hôm nay!
Tags: #TypeScript #CloudflareWorkers #Serverless #WebDevelopment #Tutorial2025
Cập nhật: 17 Tháng 11, 2025
Tác giả: WordPress Post Manager Team