# Send and receive email with Express

## Install

```bash
npm install voozin express
```

## Send email

```ts
import express from "express";
import { Voozin, VoozinError } from "voozin";

const voozin = new Voozin(process.env.VOOZIN_API_KEY);
const app = express();

app.post("/password-reset", express.json(), async (req, res) => {
  const user = await findUserByEmail(req.body.email);
  if (user) {
    const token = await createResetToken(user);
    try {
      await voozin.emails.send(
        {
          from: "Acme <no-reply@acme.com>",
          to: [user.email],
          template_id: "password-reset",
          variables: { first_name: user.firstName, reset_url: `https://acme.com/reset/${token.value}` },
        },
        { idempotencyKey: `reset-${token.id}` },
      );
    } catch (err) {
      if (err instanceof VoozinError) console.error("Voozin", err.statusCode, err.message);
      throw err;
    }
  }
  res.status(204).end();
});
```

## Receive webhooks

The signature is computed over the raw body, so the webhook route must not go through `express.json()`. Use `express.raw` on that route:

```ts
import { webhookHandler } from "voozin/express";

app.post(
  "/webhooks/voozin",
  express.raw({ type: "application/json" }),
  webhookHandler({
    secret: process.env.VOOZIN_WEBHOOK_SECRET!,
    async onEvent(event) {
      if (event.type === "inbound.received") {
        await tickets.createFromEmail(event.data);
      }
    },
  }),
);
```

`webhookHandler` responds `204` after `onEvent` resolves, `400` for an invalid signature, and passes other errors to Express's error handler, so Voozin retries the delivery.

If you mount a global `express.json()`, register the webhook route before it.

## Without the helper

```ts
import { verifyWebhook, WebhookVerificationError } from "voozin";

app.post("/webhooks/voozin", express.raw({ type: "application/json" }), async (req, res) => {
  try {
    const event = await verifyWebhook(req.body, req.headers, process.env.VOOZIN_WEBHOOK_SECRET!);
    await handle(event);
    res.status(204).end();
  } catch (err) {
    res.status(err instanceof WebhookVerificationError ? 400 : 500).end();
  }
});
```

The same code works with Fastify (`request.rawBody` with `fastify-raw-body`), Hono (`await c.req.text()`) and plain `node:http`.
