Deploy serverless edge computing applications on Cloudflare's global network with Workers, KV storage, Durable Objects, and AI inference capabilities.
Deploy and manage serverless applications on Cloudflare's global edge network with zero infrastructure configuration.
Cloudflare Workers is a serverless platform for building, deploying, and scaling applications across Cloudflare's global network. It enables fast performance with high reliability anywhere in the world, supports multiple programming languages (JavaScript, TypeScript, Python, Rust), and provides built-in observability with flexible pricing.
**Install Wrangler CLI:**
```bash
npm install -g wrangler
pnpm add -g wrangler
```
**Authenticate with Cloudflare:**
```bash
wrangler login
```
**Create from template:**
```bash
wrangler init my-worker
cd my-worker
```
**Select project options:**
**Basic Worker structure (TypeScript/JavaScript):**
```typescript
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return new Response('Hello World!');
},
};
```
**With bindings (KV example):**
```typescript
export interface Env {
MY_KV: KVNamespace;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const value = await env.MY_KV.get('myKey');
return new Response(value || 'Not found');
},
};
```
**Test locally:**
```bash
wrangler dev
```
This starts a local development server with hot reload.
**Edit `wrangler.toml`:**
```toml
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2024-01-01"
[[kv_namespaces]]
binding = "MY_KV"
id = "your-kv-namespace-id"
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "your-database-id"
[vars]
ENVIRONMENT = "production"
```
**Create KV namespace:**
```bash
wrangler kv:namespace create "MY_KV"
```
**Create D1 database:**
```bash
wrangler d1 create my-database
```
**Set secrets (encrypted):**
```bash
wrangler secret put API_KEY
```
**Use in Worker:**
```typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const apiKey = env.API_KEY; // Access secret
// Use apiKey for external API calls
},
};
```
**Deploy to production:**
```bash
wrangler deploy
```
**Deploy to specific environment:**
```bash
wrangler deploy --env staging
```
**View deployment URL:**
```
https://my-worker.<your-subdomain>.workers.dev
```
**Add custom domain in `wrangler.toml`:**
```toml
routes = [
{ pattern = "example.com/*", zone_name = "example.com" }
]
```
**Or via Cloudflare Dashboard:**
**View real-time logs:**
```bash
wrangler tail
```
**Access metrics:**
**Enable Logpush (for persistent logs):**
**Add scheduled events in `wrangler.toml`:**
```toml
[triggers]
crons = ["0 0 * * *"] # Daily at midnight UTC
```
**Handle in Worker:**
```typescript
export default {
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise<void> {
// Run background job
await fetch('https://api.example.com/cleanup');
},
};
```
**Durable Objects (stateful storage):**
```typescript
export class Counter {
state: DurableObjectState;
constructor(state: DurableObjectState, env: Env) {
this.state = state;
}
async fetch(request: Request) {
let count = (await this.state.storage.get<number>('count')) || 0;
count++;
await this.state.storage.put('count', count);
return new Response(`Count: ${count}`);
}
}
```
**Workers AI (LLM inference):**
```typescript
const response = await env.AI.run('@cf/meta/llama-2-7b-chat-int8', {
prompt: 'What is Cloudflare Workers?',
});
```
**Queues (message passing):**
```typescript
await env.MY_QUEUE.send({ userId: 123, action: 'process' });
```
**Local testing with Miniflare:**
```bash
wrangler dev --local
```
**Unit tests with Vitest:**
```bash
npm install -D vitest @cloudflare/vitest-pool-workers
npx vitest
```
**Example test:**
```typescript
import { env, createExecutionContext } from 'cloudflare:test';
import worker from './index';
test('returns Hello World', async () => {
const request = new Request('http://localhost/');
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
expect(await response.text()).toBe('Hello World!');
});
```
**GitHub Actions example:**
```yaml
name: Deploy Worker
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
```
1. **Use compatibility dates**: Always specify `compatibility_date` in `wrangler.toml` to lock runtime behavior
2. **Minimize CPU time**: Workers have CPU time limits (10ms free, 50ms paid); optimize hot paths
3. **Leverage edge caching**: Use Cache API for static assets and computed responses
4. **Handle errors gracefully**: Return proper HTTP status codes and error messages
5. **Use bindings over fetch**: Bindings are faster and more secure than external HTTP calls
6. **Test locally first**: Use `wrangler dev` extensively before deploying
7. **Version your Workers**: Use gradual deployments and rollbacks for safe releases
8. **Monitor metrics**: Set up alerts for error rates, latency spikes, and CPU usage
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/cloudflare-workers-development/raw