DEVELOPER GUIDE · CONTACT FORMS
Connect an Astro contact form
Keep your Astro frontend. Connect a provisioned form through your client website’s same-origin proxy, read its schema and submit JSON.
The public OpenAPI source can be read directly by coding agents and API tools without signing in. It covers the public form schema and submission endpoints plus authenticated admin operations. Its servers entry names production; configure your tool with your provisioned backend origin when working in another environment.
01Start with personal setup
Access is by invitation. Request early access to discuss a project; this does not create an account or activate a service. Before this example can send to a real backend, we must provision a workspace, an environment and an active form-environment binding.
- Agree the field keys, types, limits, locales, anti-spam settings and retention. The example schema below assumes required
emailandmessagefields; it is not a default template that already exists for your account. - Allowlist the exact website
Origin, including scheme and non-default port:https://www.example.comdiffers fromhttps://example.com. Provision preview and production environments separately. - Obtain the form-environment UUID; the backend is always
app.site-services.squibble.ch. The UUID is a public routing identifier, sometimes called a form token; it is not a secret or an API key. - Create the form environment’s API key. Your server sends it as
Authorization: Bearer, never the browser. There is no public or publishable key mode: the key grants one form environment and works server-to-server only. It is shown once; store it as a secret (for example the CI/CD variableSITE_SERVICES_API_KEY) and never commit it. The proxy step below shows where to find both values.
Validation and storage are implemented in source. API, storage and email notifications form the contact-form flow planned for early access. Operational email setup is pending; an operator inbox UI is planned separately. Agree and test how the responsible person will retrieve and handle legitimate requests before a client goes live.
02Configure the client website proxy
This nginx configuration belongs to the client website serving Astro. It has three files: a small http-level file with the per-visitor limit, a template with the three locations (schema, submissions and the key check) that your server block includes, and a snippet every location includes. The highlighted lines carry the two values you supply; the numbered notes below the template say where each one is. The backend host app.site-services.squibble.ch is fixed. These are exact-match locations, anchored to one UUID and three routes. The marketing website’s own ingress only exposes its provisioned submission POST; it is not a schema proxy for client projects.
# /etc/nginx/conf.d/site-services-limits.conf
# One bucket per visitor for the Site Services form routes, so a single visitor cannot use up
# the budget Site Services gives your whole proxy. Same budget as Site Services' own per-visitor limit.
limit_req_zone $binary_remote_addr zone=site_services_forms:10m rate=6r/m;The limit gives each visitor its own budget at your proxy, so one visitor cannot use up what Site Services allows your whole proxy. If nginx sits behind a CDN or load balancer, configure set_real_ip_from and real_ip_header first: otherwise $remote_addr is the edge, and all visitors share one budget here and at Site Services.
# Keep this file as /etc/nginx/templates/site-services.locations.template. The official nginx
# image renders it with envsubst at start to /etc/nginx/conf.d/site-services.locations, filling
# ${SITE_SERVICES_API_KEY} from the server environment; the key never reaches the browser or the build.
# No .conf suffix, so nginx does not load it at http level. Inside the CLIENT WEBSITE's HTTPS
# server block: include /etc/nginx/conf.d/site-services.locations;
location = /api/site-services/forms/<YOUR_FORM_ENVIRONMENT_UUID>/schema {
limit_except GET { deny all; }
proxy_pass https://app.site-services.squibble.ch/api/v1/forms/<YOUR_FORM_ENVIRONMENT_UUID>/schema;
include /etc/nginx/snippets/site-services-upstream.conf;
# The schema is public; never forward a visitor's Authorization header.
proxy_set_header Authorization "";
}
location = /api/site-services/forms/<YOUR_FORM_ENVIRONMENT_UUID>/submissions {
limit_except POST { deny all; }
limit_req zone=site_services_forms burst=5 nodelay;
limit_req_status 429;
proxy_pass https://app.site-services.squibble.ch/api/v1/forms/<YOUR_FORM_ENVIRONMENT_UUID>/submissions;
include /etc/nginx/snippets/site-services-upstream.conf;
# Submissions require the form environment's API key, added here on the server.
proxy_set_header Authorization "Bearer ${SITE_SERVICES_API_KEY}";
}
location = /api/site-services/forms/<YOUR_FORM_ENVIRONMENT_UUID>/key {
limit_except GET { deny all; }
limit_req zone=site_services_forms burst=5 nodelay;
limit_req_status 429;
proxy_pass https://app.site-services.squibble.ch/api/v1/forms/<YOUR_FORM_ENVIRONMENT_UUID>/key;
include /etc/nginx/snippets/site-services-upstream.conf;
# The key check answers 204 when the key below works for this form; it never counts towards a ban.
proxy_set_header Authorization "Bearer ${SITE_SERVICES_API_KEY}";
}
# Reject every other Site Services route; do not expose admin or auth.
location /api/site-services/ { return 404; }<YOUR_FORM_ENVIRONMENT_UUID>: the form environment UUID, in all six places. In the Site Services admin at app.site-services.squibble.ch, open Workspace → Forms → your form → Publications → the publication for this environment; the card “Connection” shows it as “Endpoint id” with a copy button.${SITE_SERVICES_API_KEY}: leave this as written; nginx fills it at start. On the same publication page, open “API keys” → “Create API key”. The key is shown once, in the “Copy API key” dialog: store it as the server environment variable (or CI/CD secret)SITE_SERVICES_API_KEY.
The API key stays on the server
The submissions and key-check locations add the key, read from the SITE_SERVICES_API_KEY environment variable when nginx starts. If you do not use the nginx image’s template mechanism, put those lines into an include file readable only by root. Any other server-side proxy (an Astro SSR endpoint, an edge function) must do the same: add the header, forward Origin, set X-Site-Services-Visitor-Ip to the visitor’s address and never pass on a value the visitor sent, and keep the key out of client code and the build.
Every location includes the shared upstream snippet below. It names the backend for Host, X-Forwarded-Host and TLS SNI, verifies its certificate and drops cookies. Copy it unchanged. It also passes the visitor’s address as X-Site-Services-Visitor-Ip, overwriting anything the visitor sent, so limits and bans apply to each visitor rather than to your whole proxy.
# /etc/nginx/snippets/site-services-upstream.conf
proxy_set_header Host app.site-services.squibble.ch;
proxy_set_header X-Forwarded-Host app.site-services.squibble.ch;
proxy_set_header Origin $http_origin;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Site-Services-Visitor-Ip $remote_addr;
proxy_set_header Cookie "";
proxy_ssl_server_name on;
proxy_ssl_name app.site-services.squibble.ch;
proxy_ssl_verify on;
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
proxy_intercept_errors off;
proxy_cache off;The browser calls /api/site-services/… on its own origin; nginx forwards to /api/v1/… over verified TLS. Host and TLS SNI must both name the backend, not the client website. Preserve the incoming Origin; never replace it with an allowed constant. Response status, JSON and Retry-After pass through without interception.
This example assumes nginx terminates public HTTPS directly and uses the system CA bundle at the shown Linux path. Redirect public HTTP to HTTPS. If TLS terminates at a load balancer, configure trusted proxy/real-IP handling and derive the external scheme only from that trusted hop; blindly forwarding client-supplied headers is unsafe. Set nginx’s body limit at least as high as the agreed form limit; the backend also enforces a global cap. Static-only hosting needs an equivalent server/edge proxy. Astro dev and preview do not install these nginx routes.
03Read the contract, then build the payload
GET/
A successful GET returns a raw draft 2020-12 JSON Schema, not a data/meta envelope. It is public and cacheable for 60 seconds. This illustrative response corresponds to the agreed example fields; always read your actual provisioned schema.
Example schema · 43 lines
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Contact",
"type": "object",
"properties": {
"email": {
"type": "string",
"format": "email",
"maxLength": 254,
"x-labels": {
"en": "Email",
"de": "E-Mail"
},
"x-placeholders": {}
},
"message": {
"type": "string",
"maxLength": 2000,
"x-labels": {
"en": "Message",
"de": "Nachricht"
},
"x-placeholders": {}
}
},
"required": [
"email",
"message"
],
"additionalProperties": false,
"x-site-services": {
"locales": [
"en",
"de"
],
"honeypot_field": "website",
"started_at_field": "started_at",
"min_elapsed_ms": 3000,
"max_elapsed_ms": 3600000,
"max_body_bytes": 8192,
"form_key": "contact"
}
}properties and required describe business fields only. locale and the two anti-spam fields are top-level transport metadata removed before field validation. Read their names and timing limits from x-site-services. Do not validate the whole transport body against additionalProperties: false; validate the business-field subset. The backend remains authoritative.
POST/Content-Type: application/json
{
"email": "alex@example.com",
"message": "Can we talk?",
"locale": "en",
"website": "",
"started_at": 1790000000000
}This timestamp is illustrative: capture Date.now() when the browser form becomes ready, never at build time or at submit time. Keep the honeypot empty for human visitors. Send flat JSON, not { data: … }, FormData or URL-encoded HTML. Convert booleans and integers explicitly; required boolean fields must be true. Unknown business keys fail validation.
04Use a small browser transport in Astro
Download this module to src/lib/contact-form.js in your Astro project and import its two functions in a client-side <script> in your .astro component, not its build-time frontmatter. The displayed source is the exact downloadable file exercised by the guide’s browser tests. It is a transport module, not a complete form component or JSON Schema validator.
// Browser transport only. The caller owns the form UI and catches rejected promises.
export async function loadContactForm(id, locale) {
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
throw new Error('Use the provisioned form-environment UUID');
}
const base = `/api/site-services/forms/${id}`;
const response = await fetch(`${base}/schema`, {
credentials: 'omit', signal: AbortSignal.timeout(20000),
});
if (!response.ok) throw new Error(`Schema unavailable: ${response.status}`);
const schema = await response.json(); // Raw JSON Schema, not result.data.
const rules = schema['x-site-services'];
if (!rules?.locales?.includes(locale)) throw new Error('Unsupported form locale');
return { base, schema, rules, locale, startedAt: Date.now() };
}
export async function submitContactForm(session, fields, honeypot = '') {
const { base, rules, locale, startedAt } = session;
const elapsed = Date.now() - startedAt;
if (rules.time_trap_enabled !== false) {
if (elapsed < rules.min_elapsed_ms) return { kind: 'wait' };
if (elapsed > rules.max_elapsed_ms) return { kind: 'expired' };
}
const body = JSON.stringify({
...fields, locale,
[rules.honeypot_field]: honeypot,
[rules.started_at_field]: startedAt,
});
if (new TextEncoder().encode(body).length > rules.max_body_bytes) {
return { kind: 'failed', status: 413 };
}
const response = await fetch(`${base}/submissions`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
credentials: 'omit', body, signal: AbortSignal.timeout(20000),
});
const result = await response.json();
if (response.status === 202 && result?.data?.status === 'accepted') {
return { kind: 'accepted' };
}
if (response.status === 422 && result?.errors && typeof result.errors === 'object') {
return { kind: 'invalid', errors: result.errors };
}
return { kind: 'failed', status: response.status };
}- On browser initialization,
await loadContactForm(publicFormEnvironmentId, "en")(or"de") once and retain the returned session. Obtain the public UUID from your component’s configuration. Comparesession.schemawith your rendered field keys, types and constraints; keep Send disabled if setup fails. - In the submit handler,
preventDefault(), check native validity, block concurrent sends andawait submitContactForm(session, { email: emailInput.value, message: messageInput.value }, honeypotInput.value). Use your own input references and actual schema keys. Keep the honeypot out of the keyboard and accessibility flow withtabindex="-1",aria-hidden="true"andautocomplete="off"on its hidden wrapper/input as appropriate. - Handle every result below, and catch network, timeout and non-JSON failures. Always clear the busy state in
finally. Preserve entries on failure, use anaria-livestatus, associate errors with known fields and focus the first invalid field or status. Render messages as text, never server HTML. Without JavaScript, explain that sending is unavailable and provide a real contact alternative; native HTML form submission is not supported by this JSON endpoint.
05Treat acknowledgement and errors precisely
{ "data": { "status": "accepted" }, "meta": {} }Only HTTP 202 with data.status === "accepted" produces kind: "accepted". The same response is returned for silent spam, including a filled honeypot or too-fast submission. It does not prove legitimate storage, email delivery, a human reply, account creation or an invitation.
HTTP 422 uses application/problem+json (RFC 9457). Read the top-level errors map, not data.errors. The following is an errors-member excerpt, not the entire problem document; messages are localized and can be configured.
{
"errors": {
"email": [
{
"code": "required",
"message": "This field is required."
}
]
}
}Result kinds
kind: "accepted"- Show “Request accepted” and prevent another send. Silent spam gets the same answer, so it proves neither storage nor delivery.
kind: "invalid"- Map known field keys to your UI. A started-at error (
expired,requiredorinvalid), alocaleerror or an unknown key needs form-session or configuration recovery, not an invisible field marker. kind: "wait"- Wait until
min_elapsed_mshas passed; never backdate the timestamp. kind: "expired"- Offer an explicit restart with
loadContactFormagain, keep entries and wait the new minimum interval. Never auto-resubmit. kind: "failed"- The request was refused;
statusholds the HTTP code below. Fix configuration or payload rather than retrying blindly.
HTTP status of kind: "failed"
| Status | Meaning and action |
|---|---|
| 400 | Malformed JSON. Fix the payload. |
| 401 | The proxy sent no valid API key. The problem code says why: unauthorized (missing or unknown), api_key_revoked, api_key_expired or api_key_wrong_form_environment. Fix the server environment at once (see the warning below). |
| 403 | Inactive binding, a disallowed or missing Origin, a visitor banned for filling the honeypot, or the proxy’s IP address banned after repeated unknown keys. |
| 404 | Unknown form-environment UUID. |
| 413 | Body too large for the agreed form limit. |
| 415 | Wrong media type; send application/json. |
| 429 | Too many requests – from one visitor (at your proxy or at Site Services), for the key or for the form. Pause, and honour Retry-After when provided. |
| 5xx | Service failure. Keep entries and offer a later retry. |
Check the key before go-live: only an unknown key can block the form
A missing, mistyped or never-issued key counts as a failure: by default ten within ten minutes ban the proxy’s IP address for an hour (403), which blocks the form for all visitors. A revoked or expired key, or one issued for another form environment, answers 401 with its own code (api_key_revoked, api_key_expired or api_key_wrong_form_environment) and never bans. A visitor who keeps filling the honeypot is banned alone. The key check in the verification list counts no failures: run it after every deploy and key rotation.
The minimal module returns status but not Retry-After; add header exposure in your UI adapter if implementing timed retries. A rejected promise means acceptance could not be confirmed. Preserve entries and offer manual recovery; the request might already have arrived, so an automatic retry can duplicate it.
06Verify on the actual client origin
This guide’s automated browser checks execute the downloadable module against mocked API responses. They do not establish a live nginx-to-Rails connection or prove delivery. The schema and submission contract is traced to the backend’s public controllers, schema generator and executing request specs.
- After provisioning, validate the nginx configuration and certificates.
- After every deploy and key rotation, run
curl -i https://<client-origin>/api/site-services/forms/<YOUR_FORM_ENVIRONMENT_UUID>/keyand expect204. A401names the cause in itscode; this check never counts towards a ban. - From the client origin,
GETthe schema and compare every rendered field and limit. - Check that an unrelated
/api/site-services/path returns404. - Submit a valid request after the minimum interval and check the exact
202envelope. Verify the legitimate stored record independently through the agreed operator workflow. - Check that a known invalid field returns
422after the time trap has passed. - A
401withcodeunauthorizedmeans the key is missing or mistyped in the server environment: stop, fix it and rerun the key check before sending submissions again. - Verify that a foreign or missing
Originis refused, expired sessions preserve entries and network failures do not erase input. - Check keyboard, mobile and error announcements.
- Agree a privacy notice and the operational follow-up path before go-live.