# Send Neon Auth email with Groundmail

Neon Auth (Managed Better Auth) sends sign-in codes, magic links, verification and password reset emails from a shared Neon address, `auth@mail.myneon.app`. That sender is rate-limited and can't send verification links, so Neon asks you to set up your own email provider before you go to production. Point it at Groundmail and those emails come from your own domain, and each one shows up in your Groundmail email log with its delivery status.

There are two ways:

1. **[Custom SMTP](#custom-smtp)**: paste Groundmail's SMTP settings into Neon. Five minutes, no code. Neon still writes the emails with its own templates; they just come from your address.
2. **[Webhooks](#your-own-templates-with-webhooks)**: Neon calls your code for each sign-in code and magic link, and your code sends it with `POST /emails` and your own [templates](https://docs.groundmail.dev/templates). Use this when you want the emails to look like your app.

---

## Prerequisites

- A Groundmail account with a [verified sending domain](https://docs.groundmail.dev/domains). A subdomain such as `mail.yourdomain.com` works well.
- A Neon project with Neon Auth turned on.

Until you add a payment method, Groundmail only delivers to your own account email. Add one under **Settings → Billing** before your users sign up.

---

## Custom SMTP

### 1. Create an SMTP credential

In Groundmail, open **SMTP**. Under **Create credential**, name it `Neon` and click **Create SMTP credential**, then copy the password. It's shown once.

### 2. Add it to Neon

In the Neon Console, open your project's **Settings → Better Auth**, choose **Custom SMTP provider**, and enter:

| Setting | Value |
|---------|-------|
| Host | `smtp.groundmail.dev` |
| Port | `587` |
| Username | `groundmail` |
| Password | The SMTP credential from step 1 |
| Sender email | An address on your verified domain, for example `noreply@mail.yourdomain.com` |
| Sender name | Your app's name |

Click **Save**.

Or set it with the Neon CLI, from a directory linked to your project:

```bash
neon neon-auth config email-provider update \
  --type standard \
  --host smtp.groundmail.dev \
  --port 587 \
  --username groundmail \
  --password "$GROUNDMAIL_SMTP_PASSWORD" \
  --sender-email noreply@mail.yourdomain.com \
  --sender-name "Your App"
```

Then send yourself a test through the saved settings:

```bash
neon neon-auth config email-provider test --recipient-email you@yourdomain.com
```

Port `587` uses STARTTLS. If your network blocks it, use `2525`: it's the same server with the same login. See [SMTP relay](https://docs.groundmail.dev/smtp).

### Branches

Email settings belong to a branch, so set them on the branch your production app uses. Add `--branch <name>` to the CLI commands to pick one. For preview and development branches, create a **test** SMTP credential instead (in the dashboard, switch to **Test** and open **SMTP**): its password starts `gmsmtp_test_`, every message runs the same checks as a real one, and nothing is delivered. A copy lands in your test inbox.

---

## Your own templates with webhooks

With custom SMTP, Neon still writes the emails. To send your own, subscribe a webhook to Neon Auth's `send.otp` and `send.magic_link` events. Once you do, Neon stops sending those emails itself and calls your endpoint instead, and your endpoint sends them through Groundmail.

### 1. Create the templates

Make one [template](https://docs.groundmail.dev/templates) per email in **Templates**. Two starters already fit: **Start from a template** → `email-verification` and `password-reset`. Add your own for sign-in codes and links. The handler below uses these aliases and variables:

| Neon event | Type | Template alias | Variables |
|------------|------|----------------|-----------|
| `send.otp` | `sign-in` | `sign-in-code` | `name`, `code` |
| `send.otp` | `email-verification` | `verification-code` | `name`, `code` |
| `send.otp` | `forget-password` | `reset-code` | `name`, `code` |
| `send.magic_link` | `sign-in` | `sign-in-link` | `name`, `url` |
| `send.magic_link` | `email-verification` | `email-verification` | `name`, `verify_url` |
| `send.magic_link` | `forget-password` | `password-reset` | `name`, `reset_url` |

You only need the ones your app uses. Rename them to suit you and change the map in the code.

### 2. Add the handler

This Next.js route checks Neon's signature, picks the template and sends the email. Install the SDK with `npm install groundmail` and set:

```bash
GROUNDMAIL_API_KEY=gm_your_key_here
GROUNDMAIL_FROM="Your App <noreply@mail.yourdomain.com>"
NEON_AUTH_URL=https://your-neon-auth-url   # the Auth URL from Settings → Better Auth
```

```ts
// app/api/neon-auth/route.ts
import crypto from 'node:crypto'
import { Groundmail } from 'groundmail'

const groundmail = new Groundmail(process.env.GROUNDMAIL_API_KEY!)

const TEMPLATES: Record<string, string> = {
  'send.otp:sign-in': 'sign-in-code',
  'send.otp:email-verification': 'verification-code',
  'send.otp:forget-password': 'reset-code',
  'send.magic_link:sign-in': 'sign-in-link',
  'send.magic_link:email-verification': 'email-verification',
  'send.magic_link:forget-password': 'password-reset',
}

type NeonAuthEvent = {
  event_id: string
  event_type: string
  user: { email: string; name?: string }
  event_data: {
    otp_code?: string
    otp_type?: string
    link_url?: string
    link_type?: string
  }
}

// Neon signs each webhook with Ed25519 (detached JWS). Its public keys are at
// <NEON_AUTH_URL>/.well-known/jwks.json.
let jwks: (crypto.JsonWebKey & { kid?: string })[] = []

async function publicKey(kid: string) {
  let jwk = jwks.find((k) => k.kid === kid)
  if (!jwk) {
    const res = await fetch(`${process.env.NEON_AUTH_URL}/.well-known/jwks.json`)
    jwks = (await res.json()).keys
    jwk = jwks.find((k) => k.kid === kid)
  }
  if (!jwk) throw new Error(`Unknown key ${kid}`)
  return crypto.createPublicKey({ key: jwk, format: 'jwk' })
}

// Neon sends X-Neon-* headers, plus Neon-Better-Auth-* copies that also reach
// Neon Functions. Read whichever arrived.
function neonHeader(headers: Headers, name: string) {
  return headers.get(`x-neon-${name}`) ?? headers.get(`neon-better-auth-${name}`)
}

async function verify(rawBody: string, headers: Headers): Promise<NeonAuthEvent> {
  const signature = neonHeader(headers, 'signature')
  const kid = neonHeader(headers, 'signature-kid')
  const timestamp = neonHeader(headers, 'timestamp')
  if (!signature || !kid || !timestamp) throw new Error('Missing signature headers')

  const [headerB64, emptyPayload, signatureB64] = signature.split('.')
  if (emptyPayload !== '') throw new Error('Expected a detached JWS')

  const payloadB64 = Buffer.from(rawBody, 'utf8').toString('base64url')
  const signedB64 = Buffer.from(`${timestamp}.${payloadB64}`, 'utf8').toString('base64url')
  const valid = crypto.verify(
    null,
    Buffer.from(`${headerB64}.${signedB64}`),
    await publicKey(kid),
    Buffer.from(signatureB64, 'base64url'),
  )
  if (!valid) throw new Error('Invalid signature')
  if (Date.now() - Number(timestamp) > 5 * 60 * 1000) throw new Error('Webhook too old')

  return JSON.parse(rawBody)
}

export async function POST(request: Request) {
  const rawBody = await request.text()

  let event: NeonAuthEvent
  try {
    event = await verify(rawBody, request.headers)
  } catch {
    return new Response('invalid signature', { status: 401 })
  }

  const { event_type, user, event_data } = event
  const type = event_data.otp_type ?? event_data.link_type
  const template = TEMPLATES[`${event_type}:${type}`]
  if (!template) return new Response(null, { status: 204 })

  const name = user.name ?? ''
  const url = event_data.link_url
  const variables =
    event_type === 'send.otp'
      ? { name, code: event_data.otp_code }
      : { name, url, verify_url: url, reset_url: url }

  try {
    await groundmail.emails.send({
      from: process.env.GROUNDMAIL_FROM!,
      to: user.email,
      template: { id: template, variables },
      // Neon retries with the same event_id, so a retry never sends twice.
      idempotencyKey: `neon-auth-${event.event_id}`,
    })
  } catch {
    // A 5xx makes Neon retry.
    return new Response('send failed', { status: 500 })
  }

  return new Response(null, { status: 204 })
}
```

The same code works anywhere you can read the raw request body, including a Neon Function. Read the body as text before parsing it: the signature covers the exact bytes Neon sent.

Neon waits up to the webhook's timeout (5 seconds by default, up to 10) and tries each event up to three times, with 15 seconds in total. A send to Groundmail returns in well under a second, so answer after the send, as above.

### 3. Subscribe the webhook

In the Neon Console, open **Settings → Better Auth → Webhooks**, enter your route's URL (it must be public HTTPS), and choose `send.otp` and `send.magic_link`. Or with the CLI:

```bash
neon neon-auth config webhook update \
  --enabled \
  --url https://yourapp.com/api/neon-auth \
  --enabled-events send.otp,send.magic_link
```

Webhooks belong to a branch too. Point a preview branch's webhook at your preview deployment, and give that deployment a `gm_test_` [test key](https://docs.groundmail.dev/testing): it runs every check, delivers nothing, and puts a copy in your test inbox.

If your endpoint fails all three attempts, magic link sign-in returns an error to the user, but sign-in codes and password resets still return success with nothing sent. Watch your endpoint's errors, and the **Emails** page in Groundmail, after you switch over.

---

## Send other email from Neon

For receipts, alerts and anything else your app sends, use the [Send email with Groundmail](https://neon.com/functions/templates/groundmail-email) Neon Functions template. It adds a `POST /send-email` function to your project:

```bash
neon functions new groundmail-email
```

To keep a record of delivery, bounce and inbound email events in your own Postgres tables, subscribe a [webhook](https://docs.groundmail.dev/webhooks) and store each event.

---

## Check it works

Sign in with an email code, or request a password reset, for a test user. The email arrives from your address and is listed under **Emails** in Groundmail with its delivery status. Bounces and complaints are handled there like any other email.

---

## Troubleshooting

| Problem | Fix |
|---------|-----|
| Authentication failed | The username is `groundmail` for every account. The password is the SMTP credential, not your API key. Create a new credential if you lost it. |
| The Neon test email times out | Check the port is `587` or `2525`. If your network blocks `587`, use `2525`. |
| `domain is not verified` | The sender email must be on a domain you verified under **Domains**. |
| Emails still come from `auth@mail.myneon.app` | The settings are on a different branch. Set them on the branch your app's Neon Auth URL belongs to. |
| Webhook returns `401` | `NEON_AUTH_URL` doesn't match the branch that sent the event, so the key isn't found. Use that branch's Auth URL. |
| Email arrives with an empty name or link | The template's variable names don't match the map in the handler. Check them under **Templates**. |
