ExampleFunctions · Triggers · Secrets

DB Trigger + Email

Automatically send a welcome email whenever a new user is created in the database, using a DB trigger and a Koolbase Function with a Resend secret.

1. Add the secret

Navigate to your project → Secrets → add a secret named RESEND_API_KEY with your Resend API key value.

2. Deploy the function

Navigate to Functions → Deploy. Name it send-welcome-email, set timeout to 10s, and paste this code:

send-welcome-email/index.tsTypeScript
export async function handler(ctx) {
  const { event, collection, payload } = ctx.request;

  // Only handle record creation in the users collection
  if (event !== 'db.record.created' || collection !== 'users') {
    return { skipped: true };
  }

  const email = payload?.data?.email;
  const name  = payload?.data?.name ?? 'there';

  if (!email) {
    throw new Error('No email in user record payload');
  }

  const apiKey = Deno.env.get('RESEND_API_KEY');
  if (!apiKey) {
    throw new Error('RESEND_API_KEY secret is not configured');
  }

  const res = await fetch('https://api.resend.com/emails', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      from: 'MyApp <hello@myapp.com>',
      to: [email],
      subject: 'Welcome to MyApp!',
      html: `
        <h1>Welcome, ${name}!</h1>
        <p>Your account is ready. Get started now.</p>
      `,
    }),
  });

  if (!res.ok) {
    const err = await res.text();
    throw new Error(`Resend API error: ${err}`);
  }

  return { sent: true, email };
}

3. Create the trigger

Navigate to Functions → select send-welcome-email → Triggers tab → Add Trigger.

Function

send-welcome-email

Event

db.record.created

Collection

users

4. Test it

Use the Test button on the trigger row. Enter a sample payload and click Run Test — the mock DB is used, but the real Resend API will be called:

{
  "id": "test-user-123",
  "data": {
    "email": "test@example.com",
    "name": "Test User"
  },
  "created_at": "2026-01-01T00:00:00Z"
}

Real email sent in test mode

Test mode mocks the Koolbase DB but external API calls (Resend) still execute. Add a guard if you want to skip the email in test mode: if (ctx.request.__test) return { skipped: true }

5. Create a user from Flutter

Now whenever you insert a record into the users collection, the trigger fires and the email is sent automatically:

lib/auth.dartDart
await Koolbase.db.collection('users').insert({
  'email': 'newuser@example.com',
  'name': 'New User',
});
// Trigger fires automatically — welcome email sent