Can i create custom web hook with cloudflare workers?

I have a third party form builder which i'm embedding on my website. it accepts a webhook url. i want to connect a webhook url and capture the form submission data and push it to D1. Is it possible to do such a setup with cloudflare workers? for context I'm already running my wesbite on astro+cf
4 Replies
Erisa
Erisa•3mo ago
Its possible yes
Zeeshan
Zeeshan•3mo ago
wow thanks, that is so cool! i asked claude and it said its possible with some example code but wanted to confirm. so, i suppose i would need to create an file inside /api folder on my astro project and write a worker script there exporting a post function. then i guess i can use it like this https://my-domain.com/api/{webhook-file-name}
export async function post({ request }) {
try {
const data = await request.json();

// Log the form submission data
console.log('Form submission received:', data);

// write sql query to insert to d1 database
// await Astro.locals.runtime.env.DB.prepare("INSERT INTO contact_form........

return new Response(JSON.stringify({ message: 'Webhook received successfully' }), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
} catch (error) {
console.error('Error processing webhook:', error);
return new Response(JSON.stringify({ error: 'Error processing webhook' }), {
status: 500,
headers: {
'Content-Type': 'application/json'
}
});
}
}
export async function post({ request }) {
try {
const data = await request.json();

// Log the form submission data
console.log('Form submission received:', data);

// write sql query to insert to d1 database
// await Astro.locals.runtime.env.DB.prepare("INSERT INTO contact_form........

return new Response(JSON.stringify({ message: 'Webhook received successfully' }), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
} catch (error) {
console.error('Error processing webhook:', error);
return new Response(JSON.stringify({ error: 'Error processing webhook' }), {
status: 500,
headers: {
'Content-Type': 'application/json'
}
});
}
}
Am i right?
Zeeshan
Zeeshan•2mo ago
I build my first webhook 🎉 Following up, is there a way to call D1 db within /api route?
No description
Zeeshan
Zeeshan•2mo ago
nvm, followed this guide and got it working. basically we need to add binding. https://developers.cloudflare.com/pages/framework-guides/deploy-an-astro-site/#use-bindings-in-your-astro-application
Cloudflare Docs
Astro · Cloudflare Pages docs
Astro is an all-in-one web framework for building fast, content-focused websites. By default, Astro builds websites that have zero JavaScript runtime …
Want results from more Discord servers?
Add your server