🎉 Announcing our $3 million seed round
Logo
Getting Started

Threshold Email

Only available in OpenMeter Cloud
Sign Up

OpenMeter webhooks enable you to send usage threshold email notifications to your team and customers.

Configuring Webhook With Threshold

Configure your webhook on the OpenMeter Cloud UI with the desired interval and query period. For example, to send daily usage threshold email notifications about current month usage, you can set the interval to daily and period to CURRENT_MONTH.

Setting Threshold

To configure the usage threshold, set filter as: { usage: { $gte: 100 } }

Available filters are: $gt, $gte, $lt, $lte, $eq, $ne, $in, and $nin.

You can also filter for specific subjects as filter: { subject: { $in: ["customer-1", "customer-2"] } }.

Sending Threshold Email

To send out emails when a customer reaches the defined threshold, we are listening on the OpenMeter webhooks. When we receive the webhook we use Resend to send out email notifications. Resend is a transactional email service that allows you to send emails using a simple API and React.

Let's see the following Next.js example that consumes webhooks and sends out emails.

import { Resend } from 'resend';
import { EmailTemplate } from '../../components/EmailTemplate';
 
const resend = new Resend(process.env.RESEND_API_KEY);
 
// Listening on the webhook endpoint
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== "POST") {
    res.status(405).json({});
    return;
  }
  const msg = (await buffer(req)).toString();
 
  // See webhooks docs about how to verify signatures
  if (msg.type === "report.meter") {
    const emailTo = getEmailBySubject(msg.query.subject)
 
    // TODO: check if the user has already received an email for this overage
    // You can use the `msg.query.from` and `email` as the idempotency key.
 
    const data = await resend.emails.send({
      from: 'Acme <[email protected]>',
      to: [emailTo],
      subject: 'You reached 90% of your plan limit',
      react: EmailTemplate({ usage: msg.usage, meter: msg.meter }),
    });
 
    res.status(200).json(data);
  }
 
  res.status(400).json({ message: "Unknown event type" });
  return;
}

Note that the webhook will be called for every period you defined in your report. To avoid duplicate emails, you must check if the user has already received an email for the given period. To identify duplicates, you can use the msg.query.from and email fields as the idempotency key. In our example, the from will point to the first day of the month as we picked CURRENT_MONTH as period.

Last edited on April 25, 2024