Publish to a Queue via Workers
Publish to a Queue directly from your Worker.
The following example shows you how to publish messages to a Queue from a Worker. The example uses a Worker that receives a JSON payload from the request body and writes it as-is to the Queue, but in a real application you might have more logic before you queue a message.
- A queue created via the Cloudflare dashboard ↗ or the wrangler CLI.
- A configured producer binding in the Cloudflare dashboard or Wrangler file.
Configure your Wrangler file as follows:
{ "name": "my-worker", "queues": { "producers": [ { "queue": "my-queue", "binding": "YOUR_QUEUE" } ] }}
name = "my-worker"
[[queues.producers]] queue = "my-queue" binding = "YOUR_QUEUE"
The following Worker script:
- Validates that the request body is valid JSON.
- Publishes the payload to the queue.
interface Env { YOUR_QUEUE: Queue;}
export default { async fetch(req, env): Promise<Response> { // Validate the payload is JSON // In a production application, we may more robustly validate the payload // against a schema using a library like 'zod' let messages; try { messages = await req.json(); } catch (e) { // Return a HTTP 400 (Bad Request) if the payload isn't JSON return Response.json({ err: "payload not valid JSON" }, { status: 400 }); }
// Publish to the Queue try { await env.YOUR_QUEUE.send(messages); } catch (e: any) { console.log(`failed to send to the queue: ${e}`); // Return a HTTP 500 (Internal Error) if our publish operation fails return Response.json({ error: e.message }, { status: 500 }); }
// Return a HTTP 200 if the send succeeded! return Response.json({ success: true }); },} satisfies ExportedHandler<Env>;
To deploy this Worker:
npx wrangler deploy
To make sure you successfully write a message to your queue, use curl
on the command line:
# Make sure to replace the placeholder with your shared secretcurl -XPOST "https://YOUR_WORKER.YOUR_ACCOUNT.workers.dev" --data '{"messages": [{"msg":"hello world"}]}'
{"success":true}
This will issue a HTTP POST request, and if successful, return a HTTP 200 with a success: true
response body.
- If you receive a HTTP 400, this is because you attempted to send malformed JSON to your queue.
- If you receive a HTTP 500, this is because the message was not written to your Queue successfully.
You can use wrangler tail
to debug the output of console.log
.
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Products
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark