cloudflare-workers-runtime-apis
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudflare Workers Runtime APIs
Cloudflare Workers Runtime API
Master the Workers runtime APIs: Fetch, Streams, Crypto, Cache, WebSockets, and text encoding.
掌握 Workers 运行时 API:Fetch、Streams、Crypto、Cache、WebSockets 和文本编码。
Quick Reference
快速参考
| API | Purpose | Common Use |
|---|---|---|
| Fetch | HTTP requests | External APIs, proxying |
| Streams | Data streaming | Large files, real-time |
| Crypto | Cryptography | Hashing, signing, encryption |
| Cache | Response caching | Performance optimization |
| WebSockets | Real-time connections | Chat, live updates |
| Encoding | Text encoding | UTF-8, Base64 |
| API | 用途 | 常见场景 |
|---|---|---|
| Fetch | HTTP 请求 | 外部 API、代理 |
| Streams | 数据流式传输 | 大文件处理、实时数据 |
| Crypto | 加密操作 | 哈希、签名、加密 |
| Cache | 响应缓存 | 性能优化 |
| WebSockets | 实时连接 | 聊天、实时更新 |
| Encoding | 文本编码 | UTF-8、Base64 |
Quick Start: Fetch API
快速入门:Fetch API
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Basic fetch
const response = await fetch('https://api.example.com/data');
// With options
const postResponse = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${env.API_KEY}`,
},
body: JSON.stringify({ name: 'John' }),
});
// Clone for multiple reads
const clone = response.clone();
const json = await response.json();
const text = await clone.text();
return Response.json(json);
}
};typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Basic fetch
const response = await fetch('https://api.example.com/data');
// With options
const postResponse = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${env.API_KEY}`,
},
body: JSON.stringify({ name: 'John' }),
});
// Clone for multiple reads
const clone = response.clone();
const json = await response.json();
const text = await clone.text();
return Response.json(json);
}
};Critical Rules
重要规则
- Always set timeouts for external requests - Workers have a 30s limit, external APIs can hang
- Clone responses before reading body - Body can only be read once
- Use streaming for large payloads - Don't buffer entire response in memory
- Cache external API responses - Reduce latency and API costs
- Handle Crypto operations in try/catch - Invalid inputs throw errors
- WebSocket hibernation for cost - Use Durable Objects with hibernation
- 始终为外部请求设置超时时间 - Workers 有 30 秒的限制,外部 API 可能会挂起
- 读取响应体前先克隆 - 响应体只能读取一次
- 大负载使用流式传输 - 不要在内存中缓冲整个响应
- 缓存外部 API 响应 - 降低延迟和 API 成本
- 在 try/catch 中处理 Crypto 操作 - 无效输入会抛出错误
- WebSocket 休眠以节省成本 - 使用支持休眠的 Durable Objects
Top 10 Errors Prevented
十大可预防错误
| Error | Symptom | Prevention |
|---|---|---|
| Body already read | | Clone response before reading |
| Fetch timeout | Request hangs, worker times out | Use |
| Invalid JSON | | Check content-type before parsing |
| Stream locked | | Don't read stream multiple times |
| Crypto key error | | Validate key format and algorithm |
| Cache miss | Returns | Check cache before returning |
| WebSocket close | Connection drops unexpectedly | Handle close event, implement reconnect |
| Encoding error | | Use TextEncoder/TextDecoder properly |
| CORS blocked | Browser rejects response | Add proper CORS headers |
| Request size | | Stream large uploads |
| 错误 | 症状 | 预防措施 |
|---|---|---|
| 响应体已读取 | | 读取前克隆响应 |
| Fetch 超时 | 请求挂起,Worker 超时 | 使用带超时的 |
| 无效 JSON | | 解析前检查内容类型 |
| 流已锁定 | | 不要多次读取流 |
| Crypto 密钥错误 | | 验证密钥格式和算法 |
| 缓存未命中 | 返回 | 返回前检查缓存 |
| WebSocket 关闭 | 连接意外断开 | 处理关闭事件,实现重连 |
| 编码错误 | | 正确使用 TextEncoder/TextDecoder |
| CORS 被阻止 | 浏览器拒绝响应 | 添加正确的 CORS 头 |
| 请求过大 | | 流式传输大文件上传 |
Fetch API Patterns
Fetch API 模式
With Timeout
带超时
typescript
async function fetchWithTimeout(url: string, timeout: number = 5000): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { signal: controller.signal });
return response;
} finally {
clearTimeout(timeoutId);
}
}typescript
async function fetchWithTimeout(url: string, timeout: number = 5000): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { signal: controller.signal });
return response;
} finally {
clearTimeout(timeoutId);
}
}With Retry
带重试
typescript
async function fetchWithRetry(
url: string,
options: RequestInit = {},
retries: number = 3
): Promise<Response> {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) return response;
// Retry on 5xx errors
if (response.status >= 500 && i < retries - 1) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
continue;
}
return response;
} catch (error) {
if (i === retries - 1) throw error;
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
throw new Error('Max retries exceeded');
}typescript
async function fetchWithRetry(
url: string,
options: RequestInit = {},
retries: number = 3
): Promise<Response> {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) return response;
// Retry on 5xx errors
if (response.status >= 500 && i < retries - 1) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
continue;
}
return response;
} catch (error) {
if (i === retries - 1) throw error;
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
throw new Error('Max retries exceeded');
}Streams API
Streams API
Transform Stream
转换流
typescript
function createUppercaseStream(): TransformStream<string, string> {
return new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
}
});
}
// Usage
const response = await fetch('https://example.com/text');
const transformed = response.body!
.pipeThrough(new TextDecoderStream())
.pipeThrough(createUppercaseStream())
.pipeThrough(new TextEncoderStream());
return new Response(transformed);typescript
function createUppercaseStream(): TransformStream<string, string> {
return new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
}
});
}
// Usage
const response = await fetch('https://example.com/text');
const transformed = response.body!
.pipeThrough(new TextDecoderStream())
.pipeThrough(createUppercaseStream())
.pipeThrough(new TextEncoderStream());
return new Response(transformed);Stream Large Response
流式传输大响应
typescript
async function streamLargeFile(url: string): Promise<Response> {
const response = await fetch(url);
// Stream directly without buffering
return new Response(response.body, {
headers: {
'Content-Type': response.headers.get('Content-Type') || 'application/octet-stream',
},
});
}typescript
async function streamLargeFile(url: string): Promise<Response> {
const response = await fetch(url);
// Stream directly without buffering
return new Response(response.body, {
headers: {
'Content-Type': response.headers.get('Content-Type') || 'application/octet-stream',
},
});
}Crypto API
Crypto API
Hashing
哈希
typescript
async function sha256(data: string): Promise<string> {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}typescript
async function sha256(data: string): Promise<string> {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}HMAC Signing
HMAC 签名
typescript
async function signHMAC(key: string, data: string): Promise<string> {
const encoder = new TextEncoder();
const keyData = encoder.encode(key);
const dataBuffer = encoder.encode(data);
const cryptoKey = await crypto.subtle.importKey(
'raw',
keyData,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
const signature = await crypto.subtle.sign('HMAC', cryptoKey, dataBuffer);
return btoa(String.fromCharCode(...new Uint8Array(signature)));
}typescript
async function signHMAC(key: string, data: string): Promise<string> {
const encoder = new TextEncoder();
const keyData = encoder.encode(key);
const dataBuffer = encoder.encode(data);
const cryptoKey = await crypto.subtle.importKey(
'raw',
keyData,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
const signature = await crypto.subtle.sign('HMAC', cryptoKey, dataBuffer);
return btoa(String.fromCharCode(...new Uint8Array(signature)));
}Cache API
Cache API
typescript
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const cache = caches.default;
const cacheKey = new Request(request.url, { method: 'GET' });
// Check cache
let response = await cache.match(cacheKey);
if (response) {
return response;
}
// Fetch and cache
response = await fetch(request);
response = new Response(response.body, response);
response.headers.set('Cache-Control', 'public, max-age=3600');
// Store in cache (don't await)
ctx.waitUntil(cache.put(cacheKey, response.clone()));
return response;
}
};typescript
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const cache = caches.default;
const cacheKey = new Request(request.url, { method: 'GET' });
// Check cache
let response = await cache.match(cacheKey);
if (response) {
return response;
}
// Fetch and cache
response = await fetch(request);
response = new Response(response.body, response);
response.headers.set('Cache-Control', 'public, max-age=3600');
// Store in cache (don't await)
ctx.waitUntil(cache.put(cacheKey, response.clone()));
return response;
}
};WebSockets (Durable Objects)
WebSockets(Durable Objects)
typescript
// Durable Object with WebSocket hibernation
export class WebSocketRoom {
state: DurableObjectState;
constructor(state: DurableObjectState) {
this.state = state;
}
async fetch(request: Request): Promise<Response> {
const upgradeHeader = request.headers.get('Upgrade');
if (upgradeHeader !== 'websocket') {
return new Response('Expected websocket', { status: 426 });
}
const pair = new WebSocketPair();
const [client, server] = Object.values(pair);
// Accept with hibernation
this.state.acceptWebSocket(server);
return new Response(null, { status: 101, webSocket: client });
}
async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
// Handle incoming message
const data = typeof message === 'string' ? message : new TextDecoder().decode(message);
// Broadcast to all connected clients
for (const client of this.state.getWebSockets()) {
client.send(data);
}
}
async webSocketClose(ws: WebSocket, code: number, reason: string) {
ws.close(code, reason);
}
}typescript
// Durable Object with WebSocket hibernation
export class WebSocketRoom {
state: DurableObjectState;
constructor(state: DurableObjectState) {
this.state = state;
}
async fetch(request: Request): Promise<Response> {
const upgradeHeader = request.headers.get('Upgrade');
if (upgradeHeader !== 'websocket') {
return new Response('Expected websocket', { status: 426 });
}
const pair = new WebSocketPair();
const [client, server] = Object.values(pair);
// Accept with hibernation
this.state.acceptWebSocket(server);
return new Response(null, { status: 101, webSocket: client });
}
async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
// Handle incoming message
const data = typeof message === 'string' ? message : new TextDecoder().decode(message);
// Broadcast to all connected clients
for (const client of this.state.getWebSockets()) {
client.send(data);
}
}
async webSocketClose(ws: WebSocket, code: number, reason: string) {
ws.close(code, reason);
}
}When to Load References
何时加载参考文档
Load specific references based on the task:
- Making HTTP requests? → Load for timeout, retry, proxy patterns
references/fetch-api.md - Processing large data? → Load for TransformStream, chunking
references/streams-api.md - Encryption/signing? → Load for AES, RSA, JWT verification
references/crypto-api.md - Caching responses? → Load for Cache API patterns, TTL strategies
references/cache-api.md - Real-time features? → Load for WebSocket patterns, Durable Objects
references/websockets.md - Text encoding? → Load for TextEncoder, Base64, Unicode
references/encoding-api.md
根据任务加载特定参考文档:
- 发起 HTTP 请求? → 加载 查看超时、重试、代理模式
references/fetch-api.md - 处理大数据? → 加载 查看 TransformStream、分块处理
references/streams-api.md - 加密/签名? → 加载 查看 AES、RSA、JWT 验证
references/crypto-api.md - 缓存响应? → 加载 查看 Cache API 模式、TTL 策略
references/cache-api.md - 实时功能? → 加载 查看 WebSocket 模式、Durable Objects
references/websockets.md - 文本编码? → 加载 查看 TextEncoder、Base64、Unicode
references/encoding-api.md
Templates
模板
| Template | Purpose | Use When |
|---|---|---|
| HTTP request utilities | Building API clients |
| Stream transformation | Processing large files |
| Crypto utilities | Signing, hashing, encryption |
| WebSocket DO | Real-time applications |
| 模板 | 用途 | 使用场景 |
|---|---|---|
| HTTP 请求工具类 | 构建 API 客户端 |
| 流转换工具 | 处理大文件 |
| 加密工具类 | 签名、哈希、加密 |
| WebSocket DO | 实时应用 |
Resources
资源
- Runtime APIs: https://developers.cloudflare.com/workers/runtime-apis/
- Fetch API: https://developers.cloudflare.com/workers/runtime-apis/fetch/
- Streams API: https://developers.cloudflare.com/workers/runtime-apis/streams/
- Web Crypto: https://developers.cloudflare.com/workers/runtime-apis/web-crypto/
- Cache API: https://developers.cloudflare.com/workers/runtime-apis/cache/
- WebSockets: https://developers.cloudflare.com/workers/runtime-apis/websockets/
- 运行时 API:https://developers.cloudflare.com/workers/runtime-apis/
- Fetch API:https://developers.cloudflare.com/workers/runtime-apis/fetch/
- Streams API:https://developers.cloudflare.com/workers/runtime-apis/streams/
- Web Crypto:https://developers.cloudflare.com/workers/runtime-apis/web-crypto/
- Cache API:https://developers.cloudflare.com/workers/runtime-apis/cache/
- WebSockets:https://developers.cloudflare.com/workers/runtime-apis/websockets/