Skip to Content
Connect software

@insane-forms/core

Browser client that sends a Submission to a Form endpoint, solves the proof of work, checks Turnstile and uploads Files.

@insane-forms/core is the browser client the drop-in script and @insane-forms/react are built on. Use it when you want to send a Submission from your own JavaScript without a framework.

The package exports one function, createFormClient, and one type, SubmitResult. It has no UI. It uses browser APIs (fetch, FormData, File, btoa), so run it in the browser.

Install

npm install @insane-forms/core

The package depends on @vercel/blob (for File uploads) and altcha (for the proof of work). It ships TypeScript source.

Create a client

import { createFormClient } from "@insane-forms/core";

const client = createFormClient("https://us.insaneforms.com/f/<form-id>");
function createFormClient(
  endpoint: string,
  options?: {
    onTurnstileSiteKey?: (siteKey: string) => void;
    signal?: AbortSignal;
  },
): {
  prepare(): Promise<void>;
  submit(input: FormData | HTMLFormElement): Promise<SubmitResult>;
};

endpoint is the full, absolute URL of the Form, as shown in the app. A relative URL throws when you create the client. See the form endpoint reference for the URL and the fields it accepts.

Create one client per Form. A client asks the Form two extra things, at <endpoint>/challenge and <endpoint>/upload.

Options

onTurnstileSiteKey(siteKey) runs when the Site uses Cloudflare Turnstile. Render the Turnstile widget with that key inside your <form>. The widget adds a hidden cf-turnstile-response field, which submit reads. The client does not render the widget itself.

signal is an AbortSignal. Aborting it cancels requests and File uploads for this client. submit and prepare then reject with the signal's reason.

Prepare the client

await client.prepare();

prepare() loads the Form's spam protection and starts solving the proof of work, so the work is done by the time the Visitor presses send. Call it when a field gets focus. It resolves with no value and rejects if the Form cannot be reached or answers with something the client cannot use.

Calling prepare() is optional. submit prepares the client itself.

Send a Submission

const result = await client.submit(formElement);

submit takes an HTMLFormElement or a FormData. It reads the fields once at the start, then:

  1. Prepares the client, if prepare() has not run.
  2. Checks that a Turnstile token is present when the Form needs one.
  3. Uploads each selected File straight to storage and replaces it with a reference. Files are sent one at a time, in field order. An empty file input is skipped. More than 10 selected Files stop the send before any upload.
  4. Waits for the proof of work. The Form sets a minimum age for a proof (2 seconds at the moment), so a send can pause briefly. The client measures the proof's remaining life from the expiresInMs the Form returns, so a wrong clock on the Visitor's device does not matter. A proof that expired while waiting is replaced once. The replacement is sent even if it looks expired, and the Form decides.
  5. Posts the fields as multipart/form-data with Accept: application/json.

The post carries up to three reserved fields: _files (a JSON list of { fieldName, pathname }, present when a File was uploaded), _altcha (the proof of work, present when the Site requires it) and the cf-turnstile-response token your widget produced. Do not use these names for your own fields. The form endpoint reference lists every reserved field.

Await each submit before you start the next one on the same client.

Return value

type SubmitResult =
  | { ok: true; id: string; redirect: string }
  | { ok: false; error: string };

On success, id is the Submission's ID and redirect is where to send the Visitor: the Form's redirect URL, or the hosted thank-you page. The client does not navigate. Call window.location.assign(result.redirect) yourself, or stay on the page.

When the server turns the Submission down, submit resolves with { ok: false, error } and error is the message the Form returned, for example Empty submission, Submission too large or Too many submissions. Try again in a few minutes. Show it to the Visitor.

A Submission that the Form accepts and files as Spam still returns ok: true. The Visitor cannot tell the difference. See Spam protection.

Errors

Everything that stops the Submission before the server judges it rejects with an Error whose message is safe to show:

CauseMessage
Turnstile is required and no token is in the formComplete the verification before sending the form.
The Form cannot be preparedCould not prepare form, or the message the server returned
The proof of work cannot be solvedCould not solve challenge
More than 10 Files are selectedAttach at most 10 files.
A File upload is refusedCould not upload file, or the message the server returned (for example Invalid file)
The upload to storage failsCould not upload file. Please try again.
The network is downThe fallback message followed by Please check your connection and try again.
The response is not usableCould not send form

Wrap submit in try and catch, or use useSubmit, which turns every case into { ok: false, error }.

Example

import { createFormClient } from "@insane-forms/core";

const form = document.querySelector<HTMLFormElement>("#contact");
const status = document.querySelector<HTMLElement>("#status");
if (!form || !status) throw new Error("Missing form markup");

const client = createFormClient("https://us.insaneforms.com/f/<form-id>", {
  onTurnstileSiteKey: (siteKey) => {
    // Render the Turnstile widget inside the form with this key.
    console.info("Turnstile needed", siteKey);
  },
});

form.addEventListener(
  "focusin",
  () => {
    client.prepare().catch(() => {
      // submit() reports the failure.
    });
  },
  { once: true },
);

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  status.textContent = "Sending";
  try {
    const result = await client.submit(form);
    if (result.ok) window.location.assign(result.redirect);
    else status.textContent = result.error;
  } catch (error) {
    status.textContent =
      error instanceof Error ? error.message : "Could not send form";
  }
});

Files up to the Workspace's upload limit work through this client. A plain HTML post carries only about 4 MB of Files in total. See File uploads and Limits.

On this page