You can integrate Cloudflare Email Service with Noptin’s bounce handler to automatically stop sending emails to subscribers whose addresses hard bounce or who report your emails as spam.

Cloudflare publishes bounce and spam complaint events to a queue. In this guide, you’ll deploy a Cloudflare Worker that forwards these events to Noptin and connect it to your email sending domain.

This integration works with Cloudflare’s outbound Email Sending service, not inbound Email Routing. You don’t need to change your existing email sending configuration.

Copy your Cloudflare bounce handler URL

  1. Open Noptin > Settings > Emails in WordPress and find Bounce Handling.
  2. Select Cloudflare Email Service under Email Service.
  3. Copy the complete Cloudflare Email Service Bounce Handler URL, including its security code. Your site must be reachable over HTTPS from Cloudflare.
Cloudflare bounce handler URL

Before deploying your Worker

Make sure the domain you send from is enabled and verified in Cloudflare Email Sending. See Cloudflare’s domain configuration instructions. Your account needs access to Email Sending, Workers, and Queues; usage charges may apply.

Create a Cloudflare Worker

Choose one of the following installation methods. Automatic deployment is recommended if you have a GitHub or GitLab account. Otherwise, follow the manual instructions.

Use our preconfigured Worker to set up bounce handling without writing or editing any code. This method requires a GitHub or GitLab account.

Click the Deploy to Cloudflare button below to get started.

Deploy to Cloudflare

Sign in to Cloudflare and select the account you use for Email Sending. On the Set up your application screen, configure the following settings:

SettingWhat to do
Git accountSelect or connect your GitHub or GitLab account.
Repository nameLeave the default name.
Create private Git repositoryKeep this enabled.
Worker nameLeave the default name.
Select QueueCreate or select a queue named noptin-bounces.
NOPTIN_BOUNCE_URLPaste the complete bounce handler URL you copied from Noptin.
Enable Preview buildsTurn this off.
Protect with Cloudflare AccessLeave this disabled.
Advanced settingsLeave all settings unchanged.

Click Deploy to create your Worker.

Once deployment is complete, open Queues in your Cloudflare dashboard and confirm that:

  • noptin-bounces exists and has noptin-bounce-handler as its consumer.
  • noptin-bounces-failed exists and is configured as the dead-letter queue for the main queue.

The failed queue may appear as Disabled because it has no active consumer. You do not need to attach a consumer to this queue during normal operation.

You can now skip the manual deployment instructions and continue and continue to “Subscribe to email events”.

Option 2: Manual deployment

Use this method if you prefer to set up the Worker in the Cloudflare dashboard without connecting a Git account.

1. Create the queues

  1. Open Queues in your Cloudflare dashboard.
  2. Create a queue named noptin-bounces to receive email events.
  3. Create a second queue named noptin-bounces-failed to hold events that cannot be delivered after all retries.
Create Noptin Queues

2. Create a Worker

  1. Open Workers & Pages in the same Cloudflare account and create a Worker using the Hello World starter.
  2. Name it noptin-bounce-handler and deploy the starter Worker.
  3. Open the Worker’s code editor. Keep this tab open while you generate the code below.
Create Cloudflare Worker

3. Paste your bounce handler URL

Paste the bounce handler URL you copied from Noptin into the field below. Your Worker code will update automatically.

Paste the complete URL you copied from Noptin.

4. Copy your Worker code

Once you’ve entered your bounce handler URL, click Copy Worker code to copy the entire code to your clipboard. You don’t need to edit the code manually.

const NOPTIN_BOUNCE_URL = 'https://example.com/wp-json/noptin/v1/bounce_handler/cloudflare/REPLACE_WITH_YOUR_SECURITY_CODE';

export default {
  /**
   * Forwards hard bounces and spam complaints to Noptin,
   * retrying failed deliveries individually.
   *
   * @param {MessageBatch} batch Cloudflare Email Sending event messages.
   * @returns {Promise<void>}
   */
  async queue( batch ) {
    for ( const message of batch.messages ) {
      let stage = 'parse_event';
      let httpStatus = null;

      try {
        const event = typeof message.body === 'string'
          ? JSON.parse( message.body )
          : message.body;

        const isComplaint =
          event?.type === 'cf.email.sending.message.complained';

        const isHardBounce =
          event?.type === 'cf.email.sending.message.bounced' &&
          event?.payload?.bounce?.type === 'hard';

        // Ignore soft bounces and unrelated events.
        if ( !isComplaint && !isHardBounce ) {
          message.ack();
          continue;
        }

        // Validate the bounce handler URL.
        stage = 'validate_endpoint';

        const endpoint = new URL( NOPTIN_BOUNCE_URL );

        if (
          endpoint.protocol !== 'https:' ||
          endpoint.username ||
          endpoint.password ||
          endpoint.hash ||
          endpoint.href.includes( 'REPLACE_WITH_YOUR_SECURITY_CODE' )
        ) {
          throw new Error( 'Invalid Noptin bounce handler URL.' );
        }

        // Forward the event to Noptin.
        stage = 'http_request';

        const response = await fetch( endpoint.href, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'User-Agent': 'Noptin-Cloudflare-Bounce-Handler/1.0 (+https://noptin.com/)',
          },
          body: JSON.stringify( event ),

          // Do not follow redirects or forward sensitive event
          // data to another URL.
          redirect: 'manual',

          signal: AbortSignal.timeout( 15000 ),
        } );

        httpStatus = response.status;

        // Reject HTTP errors and redirects.
        stage = 'check_http_status';

        if ( !response.ok ) {
          throw new Error( 'HTTP request unsuccessful.' );
        }

        // A login page or firewall challenge may return HTTP 200.
        stage = 'parse_response';

        const result = await response.json();

        stage = 'check_acknowledgement';

        if ( result !== true ) {
          throw new Error( 'Noptin did not acknowledge the event.' );
        }

        // Acknowledge only after Noptin accepts the event.
        stage = 'acknowledge_message';

        message.ack();

        console.log( 'Event successfully forwarded to Noptin.' );

      } catch ( error ) {
        // Never log the private URL, email address, event body,
        // response body, or raw exception message.
        console.warn( 'Noptin bounce delivery failed; retrying.', {
          stage,
          httpStatus,
          errorType: error?.name || 'Error',
          attempt: message.attempts,
          retryDelay: 300,
        } );

        message.retry( { delaySeconds: 300 } );
      }
    }
  },
};

Having trouble with the generator? Copy the Worker code manually and replace the example URL on the first line with the bounce handler URL you copied from Noptin. Keep the quotation marks around the URL.

5. Deploy your Worker

  1. Return to your Cloudflare Worker’s code editor.
  2. Delete all the existing code in the editor.
  3. Paste the Worker code you just copied.
  4. Click Deploy to save and publish your changes.

Keep your Worker code private.

Your bounce handler URL contains a security code that authorizes changes to subscriber statuses. Do not share your URL or generated Worker code publicly.

The generator updates the code locally in your browser. It does not transmit or store your bounce handler URL.

6. Connect your Worker to the queue

  1. Open noptin-bounces in Queues and find its consumer configuration.
  2. Add a Worker consumer and select noptin-bounce-handler.
  3. Set the maximum batch size to 10, maximum retries to 100, retry delay to 300 seconds (if the setting is available), and dead-letter queue to noptin-bounces-failed. Save the consumer.
  4. In your Worker’s settings, disable its public workers.dev route and preview URLs if enabled. This Worker only receives queue messages; it does not need a public HTTP endpoint.
  5. Open your Worker’s Observability settings and enable Worker Logs if they are not already enabled. These logs help you confirm successful deliveries and troubleshoot failed requests to Noptin.

Check the connection

A hard-bounce test marks the matching subscriber as Bounced and stops future Noptin campaigns to that address. Use a separate test subscriber you control, not a customer’s address.

To test the relay without sending an email, open Queues > noptin-bounces in Cloudflare. On the Messages page, send the JSON message below. Replace [email protected] with the address of an existing test subscriber.

{
  "type": "cf.email.sending.message.bounced",
  "payload": {
    "recipient": "[email protected]",
    "bounce": {
      "type": "hard"
    }
  }
}
Cloudflare send test event

Find the address in Noptin > Subscribers and check that its status changed to Bounced. You can also filter the list to view bounced subscribers. Remove your test record afterward. This test checks the queue, Worker, and Noptin endpoint; it does not prove that Email Sending is publishing real events.

For a full check, review an actual bounce or complaint in Cloudflare’s Email Sending logs and confirm the matching subscriber status in WordPress. Check that your subscription targets the exact sending domain if real events do not arrive.

What changes in Noptin

Hard bounces mark existing subscribers as Bounced, while spam complaints mark them as Complained. Both statuses stop future Noptin campaign deliveries without deleting the subscriber. Soft bounces, including temporary bounces after all retries are exhausted, and unrelated delivery events are ignored.

Cloudflare also maintains its own suppression list. This relay does not process unsubscribe events or import existing entries from that list.

Learn how Noptin handles bounces, including subscriber status changes and their effect on campaigns.

Recover failed deliveries

If the Worker cannot deliver an event to Noptin, it automatically retries the request after five minutes. This allows your website to recover from temporary outages or other connectivity issues without losing bounce or complaint events.

Identify the cause of a failed delivery

In your Cloudflare dashboard, open Workers & Pages, select your noptin-bounce-handler Worker, and open Observability to view its logs.

Look for entries containing the message Noptin bounce delivery failed; retrying. Each entry includes diagnostic information to help you identify the cause of the failure:

  • stage — the step at which the delivery failed.
  • httpStatus — the HTTP status code returned by your website, if available.
  • errorType — the type of error encountered.
  • attempt — the current delivery attempt.

Use the following table to troubleshoot the reported failure stage.

StageWhat to check
parse_eventThe queue message does not contain valid JSON.
check_secretEnsure the NOPTIN_BOUNCE_URL secret is configured if you used automatic deployment.
validate_endpointVerify that you entered the complete HTTPS bounce handler URL copied from Noptin.
http_requestCheck whether your website is reachable and has a valid SSL certificate.
check_http_statusCheck for URL redirects, firewall restrictions, rate limits, or server errors. Refer to the reported HTTP status code.
parse_responseCheck whether a security plugin, login page, or firewall challenge is returning an unexpected response.
check_acknowledgementEnsure Noptin is active and its bounce handler is correctly configured.
acknowledge_messageCheck for errors with the Cloudflare queue consumer.

The Worker does not follow HTTP redirects. Always use the complete, final HTTPS bounce handler URL displayed in Noptin.

Recover events from the dead-letter queue

With the recommended configuration, the Worker retries failed deliveries up to 100 times, with a five-minute delay between attempts. This gives you approximately eight hours and twenty minutes to resolve the problem.

If all retries are exhausted, Cloudflare moves the event to the noptin-bounces-failed queue.

After resolving the underlying issue, follow Cloudflare’s dead-letter queue instructions to process the failed events. Review this queue promptly, as Cloudflare retains messages for a limited time.

You do not need to attach a consumer to the dead-letter queue during normal operation.

Events are delivered, but subscriber statuses do not change

If the Worker logs Event successfully forwarded to Noptin, Noptin has acknowledged the event.

If the subscriber’s status remains unchanged, verify that the recipient’s email address matches an existing subscriber in Noptin. The integration does not create new subscribers when processing bounce or complaint events.

Related Guides