Contact / feedback: Next.js Example

Last updated: Nov 27, 2026Section: Integrations

This page shows how to integrate a Contact / feedback form webhook in a Next.js app using a BFF route: the browser posts to your app, which calls Mailoo with server-held credentials. No API key on the client.

This is not the same as a Form (newsletter) integration: feedback uses POST /api/v1/webhooks/feedback/... and a CONTACT_FORM integration. For subscription forms, see website-forms{.interpreted-text role="doc"} and website-forms-nextjs-example{.interpreted-text role="doc"}. For the raw API (headers, body, CORS), see contact-feedback-form{.interpreted-text role="doc"}.

Prerequisites

  • A Mailoo project with a Contact / feedback form integration
  • Allowed origins (optional) in the integration --- when set and CORS is enforced for requests that send Origin
  • An API key with Feedback form submissions (webhook.feedback-submission) if RESTRICTED, or Full Access

Environment (server-only)

Add to .env.local (or your deployment env). All four core variables are required for the BFF to accept requests.

MAILOO_FEEDBACK_INTEGRATION_API=https://api.mailoo.app
MAILOO_FEEDBACK_INTEGRATION_API_KEY=your-api-key-here
MAILOO_FEEDBACK_INTEGRATION_PROJECT_UID=your-project-uid-here
MAILOO_FEEDBACK_INTEGRATION_ID=your-contact-form-integration-id-here

Optional (merged into every submission's metadata on the server):


# MAILOO_FEEDBACK_INTEGRATION_FORM_NAMESPACE=production-site


# MAILOO_FEEDBACK_INTEGRATION_SITE_ID=my-brand

Optional allowlist: if set, the BFF rejects submissions whose metadata.formKey (or top-level formKey) is not in the list (comma-separated). Include every formKey your UIs send (for example web-contact-page).


# MAILOO_FEEDBACK_INTEGRATION_ALLOWED_FORM_KEYS=web-contact-page,support-widget

Use server-side only; do not use NEXT_PUBLIC_* for API URL or key.

Multiple forms, one integration

You typically configure one feedback integration in env but may have several UIs (contact page, support widget, etc.). Distinguish them in the JSON body using metadata --- for example formKey (stable string per form) and entryPoint (e.g. contact_page, support_widget). The Mailoo API stores this object on the message and feedback record; see contact-feedback-form{.interpreted-text role="doc"}.

Multiple integrations, multiple BFF routes

When you need separate CONTACT_FORM integrations (different API keys, inboxes, or allowlists), create one BFF route per integration and pass a custom env prefix (or getConfig). Do not remap several integrations onto MAILOO_FEEDBACK_INTEGRATION_*.

// app/api/v1/webhooks/team-subscription/submit/route.ts
import { createFeedbackSubmitHandler } from '@mailoo/forms/routes'

export const POST = createFeedbackSubmitHandler({
  prefix: 'MAILOO_TEAM_SUBSCRIPTION_FORM',
})

Env for that route (same suffix pattern as the default feedback prefix):

MAILOO_TEAM_SUBSCRIPTION_FORM_API=https://api.mailoo.app
MAILOO_TEAM_SUBSCRIPTION_FORM_API_KEY=...
MAILOO_TEAM_SUBSCRIPTION_FORM_PROJECT_UID=...
MAILOO_TEAM_SUBSCRIPTION_FORM_INTEGRATION_ID=...

# Optional:


# MAILOO_TEAM_SUBSCRIPTION_FORM_ALLOWED_FORM_KEYS=pricing-team-request

Client hooks take an endpoint pointing at that BFF path.

BFF route handler

Prefer @mailoo/forms/routes --- do not reimplement validation or the webhook proxy.

Create app/api/v1/webhooks/feedback/submit/route.ts:

import { createFeedbackSubmitHandler } from '@mailoo/forms/routes'

export const POST = createFeedbackSubmitHandler()
// Optional: { prefix, getConfig, logger }
// Default prefix: MAILOO_FEEDBACK_INTEGRATION

The factory:

  1. Returns 503 if credentials for the bound prefix (or getConfig) are missing.
  2. Validates email / message, merges formKey into metadata, applies ${prefix}_FORM_NAMESPACE, ${prefix}_SITE_ID, and ${prefix}_ALLOWED_FORM_KEYS.
  3. Forwards to ${api}/api/v1/webhooks/feedback/${projectUid}/${integrationId} via proxyMailooWebhookJsonPost in @mailoo/next-core (Content-Type, X-API-Key, and Origin when the browser sent one --- never Referer).

Preferred config helper for layout gating:

import {
  getMailooFormsIntegrationConfig,
  MAILOO_FEEDBACK_INTEGRATION_PREFIX,
} from '@mailoo/forms'

const config = getMailooFormsIntegrationConfig({
  prefix: MAILOO_FEEDBACK_INTEGRATION_PREFIX,
})

Deprecated (still exported; do not extend): getMailooFeedbackIntegrationConfig, getMailooFormIntegrationConfig, isMailooFeedbackIntegrationConfigured.

Spam protection on the BFF (built into @mailoo/forms)

Public FORM (newsletter) and CONTACT_FORM (feedback) BFFs attract spam / subscription bombing. @mailoo/forms includes an optional host guard inside createFormSubmitHandler / createFeedbackSubmitHandler plus a token route. Mailoo API also applies a second-layer generous rate limit per integration (and per trusted client IP). Optional Cloudflare Turnstile is available when a Turnstile secret is set (default off). Double opt-in remains out of scope here.

Backward compatible: when MAILOO_FORM_SPAM_SECRET is unset, the guard is off and handlers behave as before. Client hooks that get 404 from the token route submit without a token.

Enable (env)

  • ``MAILOO_FORM_SPAM_SECRET`` --- HMAC secret for one-time tokens (required to enable; this is the GitOps env name). Optional per-binding override: ${prefix}_SPAM_SECRET.

  • ``REDIS_URL`` --- shared Redis for nonces and counters across pods (preferred; hosts usually already set this). Optional override: ${prefix}_SPAM_REDIS_URL. If Redis is down: fail-open + log, using in-memory fallback.

  • MAILOO_FORM_SPAM_ALLOWED_ORIGINS / ${prefix}_SPAM_ALLOWED_ORIGINS --- comma-separated Origins (Referer origin also checked).

  • MAILOO_FORM_SPAM_IP_HEADER / ${prefix}_SPAM_IP_HEADER --- trusted ingress IP header only (default ``x-real-ip``, e.g. Traefik). Client X-Forwarded-For is not read unless you set the header name to that intentionally.

  • ``MAILOO_FORM_TURNSTILE_SECRET_KEY`` / ${prefix}_TURNSTILE_SECRET_KEY (or spam.turnstile.secretKey) --- Cloudflare Turnstile secret key. When unset, Turnstile is off. Requires the spam guard (HMAC secret); siteverify runs after HMAC/too_fast and before rate limits (too_fast never calls siteverify; retry keeps the same captcha token).

  • MAILOO_FORM_TURNSTILE_FAIL_OPEN / ${prefix}_TURNSTILE_FAIL_OPEN / spam.turnstile.failOpen --- when siteverify is unreachable or times out: default fail-closed (captcha_unavailable 503). Set true to fail-open + log.

  • Optional: MAILOO_FORM_TURNSTILE_HOSTNAMES (comma-separated allowlist), MAILOO_FORM_TURNSTILE_ACTION, MAILOO_FORM_TURNSTILE_TIMEOUT_MS (default 5000).

  • Limits (defaults for FORM): IP 5/hour, email 1/day (key = sha256 of normalized email), global 30/hour. Feedback defaults: IP 10/hour, email 5/day, global 60/hour. Override per binding with ${prefix}_SPAM_IP_MAX / _SPAM_IP_WINDOW_MS (and the same for EMAIL / GLOBAL). Default prefixes:

  • FORM → MAILOO_CONTACT_FORM_INTEGRATION_SPAM_IP_MAX / MAILOO_CONTACT_FORM_INTEGRATION_SPAM_IP_WINDOW_MS

  • Feedback → MAILOO_FEEDBACK_INTEGRATION_SPAM_IP_MAX / MAILOO_FEEDBACK_INTEGRATION_SPAM_IP_WINDOW_MS

    Or pass spam: { ipLimit: { max, windowMs }, … } into the handler factories (secret, redisUrl, allowedOrigins, ipHeader, store for tests).

Shared public IP (CGNAT / office NAT): the BFF per-IP limit uses the public address from the trusted ingress header. Many users behind one CGNAT or corporate NAT share one bucket and may receive 429 with code: rate_limited_ip when traffic grows. Raise the env / spam.ipLimit above (defaults are unchanged). Mailoo API second layer: MAILOO_FORM_WEBHOOK_IP_MAX (default 20/hour; header MAILOO_FORM_WEBHOOK_IP_HEADER, default x-real-ip).

If the deploy also rate-limits at ingress (e.g. Traefik middleware on forms/submit), raise that limit in the ingress config as well.

Real client IP required: the IP limit is correct only when ingress sets X-Real-Ip (or the header from MAILOO_FORM_SPAM_IP_HEADER / ${prefix}_SPAM_IP_HEADER) to the browser's public IP. Otherwise every request looks like one address and the bucket becomes a site-wide limit.

Mount routes

// app/api/v1/webhooks/forms/submit/route.ts
import { createFormSubmitHandler } from '@mailoo/forms/routes'
export const POST = createFormSubmitHandler()

// app/api/v1/webhooks/forms/token/route.ts
import { createFormSpamTokenHandler } from '@mailoo/forms/routes'
export const GET = createFormSpamTokenHandler()

// Feedback: createFeedbackSubmitHandler + createFeedbackSpamTokenHandler
// e.g. app/api/v1/webhooks/feedback/token/route.ts

Token response: { success, token, issuedAt, expiresAt, minFillDelayMs } with Cache-Control: no-store.

Client

useMailooFormSubmit / useMailooFeedbackSubmit prefetch the sibling /token route on mount (and on onFormInteraction / first focus if needed), reuse an unexpired token on submit, wait until issuedAt + minFillDelayMs, and retry once after too_fast (that error does not consume the token). Send field mailooFormToken and empty honeypot mailooWebsite. For HTML forms use MailooFormHoneypotInput from @mailoo/forms/hooks. When Turnstile is enabled, pass cf-turnstile-response (widget field) or turnstileToken (mapped to cf-turnstile-response; existing widget field in values is kept). On captcha_failed / captcha_unavailable result.resetCaptcha is true (token spent). This package does not load the Turnstile script.

Error responses (BFF guard and API second layer) include a machine-readable code next to message (hooks expose result.code):

  • too_fast --- 400 (token reusable)
  • token_missing / token_invalid / token_expired / token_reused --- 400
  • rate_limited_ip / rate_limited_email / rate_limited_global --- 429 (BFF)
  • rate_limited --- 429 (Mailoo API webhook layer)
  • origin_forbidden --- 403
  • body_too_large --- 413
  • field_too_long / too_many_links --- 400
  • captcha_missing --- 400; captcha_failed --- 403; captcha_unavailable --- 503 (fail-closed default)
  • Honeypot filled → fake 200 success (no error code)

What the guard does

  1. Body / field length / link-count limits.
  2. Origin / Referer allowlist (when configured).
  3. Honeypot: filled → normal 200 success JSON, no Mailoo call.
  4. One-time HMAC token + minimum fill delay; reuse rejected; too_fast does not consume the token.
  5. Optional Cloudflare Turnstile siteverify (when secret set), with remoteip from the trusted IP header; after HMAC/too_fast, before rate limits; network/timeout fail-closed by default.
  6. Redis (or memory) rate limits: IP, sha256(email), global; Redis errors fail-open + log.
  7. Writes metadata.clientIp / metadata.clientUserAgent (IP from the trusted ingress header only).

Even when the spam guard is off, the BFF still attaches clientIp / clientUserAgent from the same trusted ingress header so the API can store them on the inbound message (and callerIp for the BFF itself).

proxyMailooWebhookJsonPost still forwards only Content-Type, X-API-Key, and Origin (never Referer). Native IP/UA fields in @mailoo/next-core are not added.

Never auto-reply or send mail to the address from the form (open relay). Prefer ingress rate limits in front of the BFF; enable Turnstile when HMAC + rate limits are not enough.

API second layer (Mailoo)

POST /api/v1/webhooks/forms/… and …/feedback/… also enforce generous in-process limits per integrationId (default 120/hour) and per integration+IP (default 20/hour, IP from MAILOO_FORM_WEBHOOK_IP_HEADER, default x-real-ip). Env: MAILOO_FORM_WEBHOOK_INTEGRATION_MAX / _WINDOW_MS, MAILOO_FORM_WEBHOOK_IP_MAX / _WINDOW_MS.

Client: POST to the BFF

From a client component, POST JSON to /api/v1/webhooks/feedback/submit with at least email and message. Include metadata.formKey (and any other context) so you can tell which form was used in the dashboard. Or use useMailooFeedbackSubmit from @mailoo/forms/hooks (token + honeypot attached automatically when the token route is enabled).

'use client'

async function submitFeedback() {
  const res = await fetch('/api/v1/webhooks/feedback/submit', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      email: 'user@example.com',
      message: 'The checkout button does nothing on mobile.',
      subject: 'Bug report',
      name: 'Jane',
      metadata: {
        formKey: 'web-contact-page',
        pageUrl: typeof window !== 'undefined' ? window.location.href : '',
      },
    }),
  })
  const data = await res.json()
  if (!res.ok) throw new Error(data.message || 'Submit failed')
  return data
}

Handle 503 (integration not configured) and 400 (validation or disallowed formKey) in your UI.

Package reference

  • Package: @mailoo/forms (createFeedbackSubmitHandler from @mailoo/forms/routes, useMailooFeedbackSubmit from @mailoo/forms/hooks) --- see nextjs-packages{.interpreted-text role="doc"}

See also

  • contact-feedback-form{.interpreted-text role="doc"} --- endpoint and JSON fields
  • website-forms-nextjs-example{.interpreted-text role="doc"} --- Form (newsletter) BFF pattern
  • nextjs-packages{.interpreted-text role="doc"} --- @mailoo/forms overview
  • OpenAPI: https://api.mailoo.app/docs/v1
  • Package READMEs: packages/forms/README.md, packages/next-core/README.md