Home / 指南 / Next.js 表單後端整合(應用程式路由器和伺服器操作)
整合指南·FRONTEND & NEXT.JS

Next.js 表單後端整合(應用程式路由器和伺服器操作)

完整的 TypeScript 和 React 實作指南,用於使用 Lugatu 端點和伺服器操作在 Next.js 14/15 中處理聯絡表單,並且零憑證暴露。

1.帶有伺服器操作的 Next.js App Router 架構

Next.js 伺服器操作專門在伺服器上執行,這使得它們非常適合使用私有 Lugatu API 金鑰提交查詢,而不會暴露客戶端捆綁包中的秘密。

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. 具有載入狀態的客戶端表單元件

將您的伺服器操作連接到具有可存取載入指示器的 React 19 / Next.js 用戶端元件。

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>
  );
}

安全性和身份驗證不變

安全說明:切勿在 LUGATU_API_KEY 前面加上 NEXT_PUBLIC_ 前綴。 只有私有伺服器端變數才能安全地保存您的即時 API 金鑰。

故障排除和常見攝取錯誤

API 金鑰請求傳回 403 FORBIDDEN_BROWSER_ORIGIN

您正在使用 API 金鑰從客戶端瀏覽器程式碼進行 fetch() 呼叫。 切換到 Next.js 伺服器操作或使用沒有 API 金鑰的公共表單端點。

常見問題解答

我可以部署到 Vercel 或 Cloudflare Pages 嗎?

是的。 伺服器操作可以跨 Next.js 支援的無伺服器平台和邊緣執行時間無縫運作。

準備好建立您的表單端點了嗎?

幾秒鐘內免費開始使用。 無需信用卡。

免費開始 →