# JavaScript and REST submissions

Last reviewed: 2026-10-16. Targets Forms API `/v1/s/:formId` and its current
response envelopes. No Forms SDK or extra HTTP client dependency is required.
Use the real dashboard endpoint, replacing `FORM_KEY` before any approved test.

## JSON and response handling

`?mode=rest` selects JSON responses; an `Accept` header alone does not. This
module exports helpers and makes no network request until called.

```ts
export async function acceptedSubmission(response: Response): Promise<void> {
  let body: unknown;
  try {
    body = await response.json();
  } catch {
    throw new Error(`Unexpected server response (HTTP ${response.status}).`);
  }
  if (
    !response.ok ||
    typeof body !== "object" ||
    body === null ||
    !("success" in body) ||
    body.success !== true
  ) {
    // A generic UI error avoids exposing raw provider text or sensitive details.
    throw new Error(`Submission was not accepted (HTTP ${response.status}).`);
  }
}

export async function submitContact(
  endpoint: string,
  fields: {
    name: string;
    email: string;
    message: string;
  },
): Promise<void> {
  const url = new URL(endpoint);
  url.searchParams.set("mode", "rest");
  const response = await fetch(url, {
    method: "POST",
    headers: { Accept: "application/json", "Content-Type": "application/json" },
    body: JSON.stringify(fields),
  });
  await acceptedSubmission(response);
}

export async function submitFiles(
  endpoint: string,
  form: HTMLFormElement,
): Promise<void> {
  const url = new URL(endpoint);
  url.searchParams.set("mode", "rest");
  const response = await fetch(url, {
    method: "POST",
    headers: { Accept: "application/json" },
    body: new FormData(form),
  });
  await acceptedSubmission(response);
}
```

For `submitFiles`, **do not set multipart Content-Type manually**: the browser
must include its generated boundary. URL-encoded fields are also supported with
`URLSearchParams`. Ensure the form's fields have `name` attributes. Send scalar
text fields for predictable rules/storage: JSON null values are omitted and
other non-string JSON values (numbers, booleans, objects, arrays) are
stringified with `JSON.stringify`, not stored as arbitrary nested typed records.

## Envelopes and common failures

Success is HTTP 200:

```json
{
  "code": 200,
  "success": true,
  "message": "Your form has been submitted successfully!",
  "url": "https://forms.basestack.co/status/success?goBackUrl=https://example.com/contact"
}
```

The illustrative `url` is server-generated from form settings. Do not hardcode
it or navigate to arbitrary response URLs without reviewing the destination.
Known request errors use their HTTP status plus
`{ error: true, code, message, url }`; unexpected 500s may have only
`{ error: true, message }`. Examples of statuses: 400 parsing/rule failures or
uploads disabled; 403 honeypot, subscription, or security restrictions; 404
unknown form; 409 disabled form; 413 oversized/too many files. Proxies or rate
limiters may return a different/non-JSON envelope. Inspect status **and** body.

In UI, set pending before awaiting fetch, disable repeat submits, catch errors,
announce a useful recoverable failure, and clear pending in `finally`. Preserve
input after failure; clear only after confirmed success. See
[React/Next.js](react-nextjs.md) or [Vue](vue.md) for complete state handling.
Do not automatically retry after a timeout: the submission may already have
been accepted and there is no documented idempotency key here.

## Verification and privacy

Mock fetch for accepted JSON, non-2xx JSON, a 200 without `success: true`, invalid
JSON, rejected network requests, and file encoding. Verify current 1 MiB/five-file
limits and dashboard retention/upload settings using
[validation/security/files](validation-security-files.md).
An accepted submission is not confirmation of webhook/email delivery. Never
send real data or trigger notifications without approval. No private API/MCP
token is needed in browser requests; keep account credentials out of frontend code.

Human docs: [JavaScript](https://docs.basestack.co/content/forms/guides/javascript),
[REST](https://docs.basestack.co/content/forms/guides/rest).
