Next.js Server Actions Integration

If you are using the Next.js App Router (v14+), the most secure way to submit forms to Forge is using Server Actions. This completely hides your API keys and form endpoint IDs from the client browser.

Why Server Actions?

  • Zero JavaScript: Simple forms work even if JS is disabled on the client.
  • Security: Your Forge API Key is never exposed in the browser network tab.
  • Performance: Less client bundle size.

Creating the Action

Create an action.ts file in your Next.js directory. This file will securely communicate with Forge.

"use server";

export async function submitToForge(formData: FormData) {
  const email = formData.get("email");
  const message = formData.get("message");

  // Keep your target endpoint as a secret environment variable
  const targetUrl = process.env.FORGE_ENDPOINT_URL;

  const res = await fetch(targetUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${process.env.FORGE_SECRET_KEY}`
    },
    body: JSON.stringify({ email, message }),
  });

  if (!res.ok) {
    throw new Error("Failed to submit form");
  }

  return { success: true };
}

Client Form Component

Now bind this server action to your standard HTML form action attribute. You can also use Next.js useFormStatus to handle loading states smoothly.

"use client";

import { submitToForge } from "./action";
// Option: use useFormStatus from react-dom for loading states

export default function ContactForm() {
  return (
    <form action={submitToForge}>
      <input name="email" type="email" required />
      <textarea name="message" required />
      <button type="submit">Send</button>
    </form>
  );
}