DwarfNinja
DwarfNinja
CDCloudflare Developers
Created by DwarfNinja on 2/19/2025 in #workers-help
Receiving webhook in a worker and sending it to the frontend?
Hey dear Cloudflare dev's, I receive a webhook from Mollie and want to forward its data to my frontend. As I understand, since workers are stateless, I can't share variables between functions eg. a global let webhook-data variable. My current approach stores the data in Cloudflare KV and then polls it to send via websockets or server-sent events, which feels overly complex and has it's own pitfalls. While Durable Objects offer in-memory state, I’m trying to keep costs low and it seems a large solution for what feels to be a small problem. Are there any suggestions how to best solve this? Thanks in advance! See the snippit below for an example of the above case:
/// server
app.post('/mollie-webhook', async (context) => {
const payload = await context.req.text()
console.log('Received webhook data:', payload)

await context.env.recurify.put('latest-payment', payload)
return context.text('Webhook received')
})

app.get('/mollie-payment-sse', async (c) => {
c.header('Content-Encoding', 'Identity');

return streamSSE(c, async (stream: SSEStreamingApi) => {
let lastEventId: string | null = null;

while (true) {
await stream.sleep(1000);

const storedEvent = await c.env.recurify.get('latest-payment');
if (storedEvent) {
const eventObj = JSON.parse(storedEvent);
if (eventObj.id !== lastEventId) {
lastEventId = eventObj.id;
await stream.writeSSE({
event: 'new-payment-update',
data: eventObj.data,
id: eventObj.id,
});
}
}
}
});
});
/// server
app.post('/mollie-webhook', async (context) => {
const payload = await context.req.text()
console.log('Received webhook data:', payload)

await context.env.recurify.put('latest-payment', payload)
return context.text('Webhook received')
})

app.get('/mollie-payment-sse', async (c) => {
c.header('Content-Encoding', 'Identity');

return streamSSE(c, async (stream: SSEStreamingApi) => {
let lastEventId: string | null = null;

while (true) {
await stream.sleep(1000);

const storedEvent = await c.env.recurify.get('latest-payment');
if (storedEvent) {
const eventObj = JSON.parse(storedEvent);
if (eventObj.id !== lastEventId) {
lastEventId = eventObj.id;
await stream.writeSSE({
event: 'new-payment-update',
data: eventObj.data,
id: eventObj.id,
});
}
}
}
});
});
9 replies