Home / Guides / Next.js Form Backend Integration (App Router & Server Actions)
INTEGRATION GUIDE · FRONTEND & NEXT.JS

Next.js Form Backend Integration (App Router & Server Actions)

Complete TypeScript and React implementation guide for handling contact forms in Next.js 14/15 using Lugatu endpoints and Server Actions with zero credential exposure.

1. Next.js App Router Architecture with Server Actions

Next.js Server Actions execute exclusively on the server, making them ideal for submitting inquiries with private Lugatu API keys without exposing secrets in client bundles.

app/actions/contact.ts typescript
'use server';

export async function submitContact(prevState: any, formData: FormData) {
  // Silent rejection of automated bot submissions via honeypot trap
  const honeypot = (formData.get('_gotcha') as string) || '';
  if (honeypot) {
    return { success: true, error: null };
  }

  const name = formData.get('name') as string;
  const email = formData.get('email') as string;
  const message = formData.get('message') as string;

  if (!name || !email || !message) {
    return { success: false, error: 'All fields are required.' };
  }

  const payload = {
    fields: { name, email, message },
  };

  try {
    const res = await fetch(`https://www.lugatu.com/api/v1/forms/${process.env.LUGATU_FORM_ID}/submissions`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.LUGATU_API_KEY}`,
        'Content-Type': 'application/json',
        'Idempotency-Key': crypto.randomUUID(),
      },
      body: JSON.stringify(payload),
    });

    if (!res.ok) {
      return { success: false, error: 'Failed to submit form.' };
    }

    return { success: true, error: null };
  } catch (err) {
    return { success: false, error: 'Network error occurred.' };
  }
}

2. Client-Side Form Component with Loading State

Connect your Server Action to a React 19 / Next.js client component with accessible loading indicators.

components/ContactForm.tsx tsx
'use client';

import { useActionState } from 'react';
import { submitContact } from '@/app/actions/contact';

export function ContactForm() {
  const [state, formAction, isPending] = useActionState(submitContact, { success: false, error: null });

  return (
    <form action={formAction} className="space-y-4 max-w-md">
      <div>
        <label className="block text-sm font-semibold mb-1">Name</label>
        <input name="name" required className="w-full border rounded-xl p-2.5" />
      </div>
      <div>
        <label className="block text-sm font-semibold mb-1">Email</label>
        <input type="email" name="email" required className="w-full border rounded-xl p-2.5" />
      </div>
      <div>
        <label className="block text-sm font-semibold mb-1">Message</label>
        <textarea name="message" rows={4} required className="w-full border rounded-xl p-2.5" />
      </div>

      <input type="text" name="_gotcha" style={{ display: 'none' }} tabIndex={-1} autoComplete="off" />

      <button type="submit" disabled={isPending} className="btn-primary-editorial w-full py-2.5">
        {isPending ? 'Sending...' : 'Send Message'}
      </button>

      {state.success && <p className="text-emerald-700 text-sm">Thank you! Your message was received.</p>}
      {state.error && <p className="text-red-700 text-sm">{state.error}</p>}
    </form>
  );
}

Security & Authentication Invariant

Security Instruction: Never prefix LUGATU_API_KEY with NEXT_PUBLIC_. Only private server-side variables can safely hold your live API key.

Troubleshooting & Common Ingestion Errors

API key request returns 403 FORBIDDEN_BROWSER_ORIGIN

You are making a fetch() call from client-side browser code with an API key. Either switch to a Next.js Server Action or use the public form endpoint without an API key.

Frequently Asked Questions

Can I deploy this to Vercel or Cloudflare Pages?

Yes. Server Actions work seamlessly across serverless platforms and edge runtimes supported by Next.js.

Ready to create your form endpoint?

Get started for free in seconds. No credit card required.

Start Free →