For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt, and this page is available as Markdown at /docs/recipes/nextjs.md.

Next.js

Two patterns for the App Router: a client component that posts from the browser, and a Server Action that submits with a server key. Hosts, IDs, and keys below are placeholders.

Warning

Never put a FormRoost server key in a NEXT_PUBLIC_ variable. Next.js inlines those into the browser bundle, where anyone can read them. Only the public submission URL may be public.

Client component

Add your dev origin, such as http://localhost:3000, to Allowed origins on the form. The browser sends Origin; no key is involved.

# .env.local
NEXT_PUBLIC_FORMROOST_URL=https://formroost.com/s/v1/sandbox/fpub_REPLACE_ME
// app/contact/contact-form.tsx
'use client'

import { useRef, useState } from 'react'

const endpoint = process.env.NEXT_PUBLIC_FORMROOST_URL!

export function ContactForm() {
  const startedAt = useRef(Date.now())
  const [status, setStatus] = useState('')

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const form = event.currentTarget
    setStatus('Sending…')
    try {
      const response = await fetch(endpoint, {
        method: 'POST',
        credentials: 'omit',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          ...Object.fromEntries(new FormData(form)),
          _fr_started_at: startedAt.current, // Unix milliseconds, as a number
        }),
      })
      if (response.status === 201) {
        form.reset()
        startedAt.current = Date.now()
        setStatus('Thanks, we received your message.')
        return
      }
      const problem = await response.json().catch(() => null)
      setStatus(
        problem?.code === 'submission_schema_invalid'
          ? 'Please check your entries.'
          : 'Something went wrong. Please try again.',
      )
    } catch {
      setStatus('Could not submit right now. Please try again.')
    }
  }

  return (
    // Keep method="post" and action so submits before hydration never leak data in a GET URL.
    <form action={endpoint} method="post" onSubmit={onSubmit}>
      <label>
        Email <input name="email" type="email" required />
      </label>
      <label>
        Message <textarea name="message" required />
      </label>
      <div aria-hidden="true" style={{ position: 'absolute', left: -10000 }}>
        <input name="_gotcha" tabIndex={-1} autoComplete="off" />
      </div>
      <button type="submit">Send</button>
      <p role="status">{status}</p>
    </form>
  )
}

Errors are RFC 9457 application/problem+json. Branch on code; see errors.

Server Action

The action runs on your server, reads a key that never reaches the browser, and sends an Idempotency-Key so a retried submit is stored once. Rotate the key after a confirmed 201, and keep the same key and field values if a submission fails so the visitor can retry without retyping.

# .env.local — server only, no NEXT_PUBLIC_ prefix.
FORMROOST_URL=https://formroost.com/s/v1/sandbox/fpub_REPLACE_ME
FORMROOST_API_KEY=fr_sandbox_REPLACE_ME
// app/contact/actions.ts
'use server'

export type SubmitResult = { ok: boolean; message: string }

export async function submitContact(input: {
  email: string
  message: string
  honeypot: string
  idempotencyKey: string
}): Promise<SubmitResult> {
  const response = await fetch(process.env.FORMROOST_URL!, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.FORMROOST_API_KEY}`,
      'Content-Type': 'application/json',
      ...(input.idempotencyKey.length >= 8
        ? { 'Idempotency-Key': input.idempotencyKey }
        : {}),
    },
    body: JSON.stringify({
      email: input.email,
      message: input.message,
      _gotcha: input.honeypot,
    }),
    cache: 'no-store',
    signal: AbortSignal.timeout(10_000),
  })
  if (response.status === 201)
    return { ok: true, message: 'Thanks, we received your message.' }
  const problem = await response.json().catch(() => null)
  console.error('FormRoost rejected the submission', response.status, problem?.code)
  return {
    ok: false,
    message:
      problem?.code === 'submission_schema_invalid'
        ? 'Please check your entries and try again.'
        : 'Something went wrong. Please try again.',
  }
}
// app/contact/server-form.tsx
'use client'

import { useState, useTransition } from 'react'

import { submitContact } from './actions'

export function ServerContactForm() {
  const [email, setEmail] = useState('')
  const [message, setMessage] = useState('')
  const [honeypot, setHoneypot] = useState('')
  // Reuse one key for retries of the same payload; rotate after a confirmed 201.
  const [idempotencyKey, setIdempotencyKey] = useState(() => crypto.randomUUID())
  const [status, setStatus] = useState('')
  const [pending, startTransition] = useTransition()

  function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    startTransition(async () => {
      try {
        const result = await submitContact({ email, message, honeypot, idempotencyKey })
        setStatus(result.message)
        if (result.ok) {
          setEmail('')
          setMessage('')
          setHoneypot('')
          setIdempotencyKey(crypto.randomUUID())
        }
      } catch {
        setStatus('Network error. Please try again.')
      }
    })
  }

  return (
    <form method="post" onSubmit={onSubmit}>
      <label>
        Email{' '}
        <input
          name="email"
          type="email"
          required
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
      </label>
      <label>
        Message{' '}
        <textarea
          name="message"
          required
          value={message}
          onChange={(e) => setMessage(e.target.value)}
        />
      </label>
      <div aria-hidden="true" style={{ position: 'absolute', left: -10000 }}>
        <input
          name="_gotcha"
          tabIndex={-1}
          autoComplete="off"
          value={honeypot}
          onChange={(e) => setHoneypot(e.target.value)}
        />
      </div>
      <button type="submit" disabled={pending}>
        {pending ? 'Sending…' : 'Send'}
      </button>
      <p role="status">{status}</p>
    </form>
  )
}

Server requests omit Origin, so production requires the bearer key. FormRoost's per-network rate limit sees your server rather than the visitor, so add your own limits in front of the action. The same code works in a Route Handler (app/api/contact/route.ts) if you prefer an HTTP endpoint. See server submissions and API keys.

Go to production

Add your live HTTPS origin, publish the configuration, change sandbox to production in both URLs, and use a production key.