Wrangler is the CLI for Cloudflare Workers — the serverless platform that runs at the edge in 300+ cities. The free tier includes 100K requests/day, making it perfect for APIs and microservices.
Installation
npm install -g wrangler
wrangler login
Create a Worker
npm create cloudflare@latest my-worker
cd my-worker
Worker Code
// src/index.ts
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/api/hello") {
return Response.json({ message: "Hello from the edge!" });
}
if (url.pathname === "/api/scrape" && request.method === "POST") {
const { targetUrl } = await request.json();
const response = await fetch(targetUrl);
const html = await response.text();
return Response.json({ length: html.length, status: response.status });
}
return new Response("Not Found", { status: 404 });
}
};
wrangler.toml Configuration
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2024-01-01"
[vars]
API_KEY = "public-value"
[[kv_namespaces]]
binding = "CACHE"
id = "your-kv-namespace-id"
[[d1_databases]]
binding = "DB"
database_name = "my-db"
database_id = "your-d1-id"
KV Storage
// Store and retrieve key-value data
await env.CACHE.put("user:123", JSON.stringify({ name: "Alex" }), { expirationTtl: 3600 });
const user = await env.CACHE.get("user:123", "json");
D1 Database (SQLite at the Edge)
const { results } = await env.DB.prepare(
"SELECT * FROM users WHERE active = ? LIMIT ?"
).bind(1, 10).all();
Deploy
# Dev server with hot reload
wrangler dev
# Deploy to production
wrangler deploy
# Deploy to staging
wrangler deploy --env staging
# Tail logs
wrangler tail
Cron Triggers
# wrangler.toml
[triggers]
crons = ["0 */6 * * *"] # Every 6 hours
export default {
async scheduled(event: ScheduledEvent, env: Env) {
// Runs on schedule
await updateCache(env);
}
};
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)