指南
Next.js 联系表单(无需后端)
Next.js 不需要自己的表单接收器。您可以把同样的原生 HTML form action 放进任何 Server Component,或者 - 如果您想要客户端的成功和错误状态 - 用一个带 fetch 的小型 Client Component。两者都直接 POST 到 Formhook。
使用原生 HTML 表单
您不需要 API 路由。表单直接 POST 到 Formhook,您的框架完全不必接触提交内容。
contact.html
<form action="https://formhook.app/f/YOUR_API_KEY" method="POST">
<label>
Email
<input type="email" name="email" required />
</label>
<label>
Message
<textarea name="message" required></textarea>
</label>
<!-- honeypot: bots fill this; humans don't see it -->
<input type="text" name="_gotcha" tabindex="-1" autocomplete="off" hidden />
<!-- optional: send users to a thank-you page after a native POST -->
<input type="hidden" name="_redirect" value="https://example.com/thanks" />
<button type="submit">Send</button>
</form>或在 Next.js 中通过 fetch 提交
如果您希望在不刷新整个页面的情况下获得客户端的成功/错误状态,使用这个版本。
components/contact-form.tsx
"use client";
import { useState } from "react";
export function ContactForm() {
const [status, setStatus] = useState<"idle" | "sending" | "ok" | "error">("idle");
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setStatus("sending");
const form = e.currentTarget;
const data = Object.fromEntries(new FormData(form));
const res = await fetch("https://formhook.app/f/YOUR_API_KEY", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
setStatus(res.ok ? "ok" : "error");
if (res.ok) form.reset();
}
if (status === "ok") return <p>Thanks - we'll be in touch.</p>;
return (
<form onSubmit={onSubmit}>
<input type="email" name="email" placeholder="Email" required />
<textarea name="message" placeholder="Message" required />
<input type="text" name="_gotcha" tabIndex={-1} hidden />
<button type="submit" disabled={status === "sending"}>
{status === "sending" ? "Sending…" : "Send"}
</button>
{status === "error" && <p>Something went wrong. Please try again.</p>}
</form>
);
}工作原理
原生 form action 可在任何 Next.js 页面或 layout 中工作,包括 Server Components。无需 app/api/contact/route.ts、Server Action 或 middleware。如果您想要带成功和错误状态的客户端 UX,第二个代码片段展示了规范模式:"use client"、useState、onSubmit、fetch 到 formhook.app/f/YOUR_API_KEY。honeypot (_gotcha) 和可选的 _redirect 与 HTML 指南中的特殊字段相同。
之后会发生什么
- 提交一秒内出现在您的 Formhook 仪表盘中。
- 推送通知会在每个启用它的设备上触发。
- 从仪表盘直接回复(Pro 及以上)- 在每个项目都有自己联系路由的客户工作中很方便。
今天就上线您的 Next.js 联系表单。
免费注册、创建表单、粘贴 API 密钥。五分钟搞定。
免费开始免费层:5 个表单 · 每月 250 次提交 · 无需信用卡。
Next.js 联系表单 - 常见问题
- 我需要添加 API 路由或 Server Action 吗?
- 不需要。表单直接 POST 到 Formhook。跳过 API 路由也意味着您自己少一个需要限速的表面,以及在 serverless 部署上少一次冷启动。
- 我能在 Server Component 中使用它吗?
- 可以 - 原生 HTML 表单代码片段在任何 Server Component 中都能工作。只有 fetch 版本需要是 Client Component,因为它使用了 useState。
- 如何在不编写速率限制 middleware 的情况下处理垃圾?
- 垃圾防护在 Formhook 一侧。honeypot 静默丢弃机器人,Cloudflare Turnstile 是仪表盘中每个表单的开关。Per-IP 和 per-form 速率限制也在服务器端强制执行。
其他框架的指南
Migrating from Formspree? See how Formhook compares.