Cloudflare Workers run at the edge - your webhook handler executes in the data center closest to the request origin, giving you sub-millisecond cold starts and global distribution.
Why Cloudflare Workers?
- Edge computing - runs in 300+ data centers worldwide
- Zero cold starts - near-instant execution
- Free tier - 100,000 requests/day
- Built-in KV storage - key-value store for caching and state
- Wrangler CLI - simple deployment workflow
Setup
Step 1: Create the Project
npm create cloudflare@latest instantdm-worker
cd instantdm-worker
Step 2: Write the Worker
// src/index.js
export default {
async fetch(request, env) {
if (request.method !== 'POST') {
return new Response('Method not allowed', { status: 405 });
}
const body = await request.json();
const { event, data } = body;
if (event === 'flow_completed') {
const name = data.response_variables?.full_name || 'there';
await fetch('https://api.instantdm.com/api-webhook', {
method: 'POST',
headers: {
'Authorization': `Bearer ${env.INSTANTDM_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'send_message',
type: 'text',
recipient_id: data.instagram_user_id,
message: `Thanks ${name}! We'll follow up shortly.`,
}),
});
}
return Response.json({ status: 'ok' });
},
};
Step 3: Set Secrets
npx wrangler secret put INSTANTDM_API_KEY
Step 4: Deploy
npx wrangler deploy
Step 5: Configure InstantDM
Paste the Worker URL into InstantDM Settings → API → Webhook URL.
Using KV for State
Store lead data in Cloudflare KV:
// In wrangler.toml, add:
// [[kv_namespaces]]
// binding = "LEADS"
// id = "your-kv-namespace-id"
await env.LEADS.put(
data.instagram_user_id,
JSON.stringify({
username: data.username,
email: data.response_variables?.email,
flow: data.flow_name,
timestamp: new Date().toISOString(),
})
);
Troubleshooting
| Issue | Solution |
|---|---|
| Worker returning 500 | Check the Workers logs in the Cloudflare dashboard. |
| Secret not available | Use wrangler secret put, not environment variables in wrangler.toml. |
| Subrequest limit | Workers have a limit of 50 subrequests per invocation. Keep API calls minimal. |
What's Next
- Deploy to Vercel for a Node.js-native option.
- Use AWS Lambda for AWS ecosystem integration.
- Read the Node.js backend guide for a traditional server.
- Explore the full API docs at instantdm.com/instagram-api-docs.