Forms: useForm, storefront endpoints and accessible messages
On this page
A form island collects what the shopper types and sends it somewhere: a newsletter list, a sign-in, a
new account. useForm() from @bizzpocket/theme/client runs the submit for you, and the storefront
host already has the endpoints to send it to. This page shows both, with validation, error and
pending states, and the accessibility rules every form must follow.
Note. The /api/... endpoints on this page belong to the BizzPocket storefront host (the one
your live store runs on). bizzpocket dev answers them for local testing: with --mock, canned
answers; with --store, only the PIN code lookup. See
Trying forms in bizzpocket dev.
useForm in depth
const { onSubmit, pending, error, done, result, reset } = useForm(submit, { validate });Put onSubmit on the form: <form onSubmit={onSubmit}>. On every submit it runs these steps, in order:
- It stops the page from reloading (
preventDefault). - It ignores the submit if the last one is still running. A double click sends one request.
- It runs the browser's own checks:
required,type="email",minLength,pattern,min,max... When one fails, the browser shows its own message next to the field, anderrorstaysnull. A form withnoValidateskips this step. - It calls
validate(data, form), if you gave one. Return a message to stop and show it aserror. Return nothing (or'') to go on. - It calls
submit(data, form).datais the form'sFormData, including the clicked submit button'snameandvalue. Return a value to finish (it becomesresult), or throw to fail.
| Member | What it is |
|---|---|
onSubmit |
the handler for <form onSubmit> |
pending |
true from step 2 until submit settles |
error |
the message of the last failure, or null. Cleared when the next submit starts. |
done |
true after a successful submit. Cleared when the next submit starts. |
result |
what the last successful submit returned |
reset() |
back to the start: not pending, no error, not done (for "Send another") |
The error message comes from what submit throws (or validate returns):
- a non-empty string: that string;
- an
Error, or any object with a non-emptymessage: itsmessage; - anything else:
Something went wrong. Please try again.
So throw a sentence written for the shopper, never a raw server message or a status code.
errorMessage(e) applies the same rule if you need it yourself.
Good to know:
submitandvalidateare read at submit time, so they may use the island's latest state.- If the island leaves the page while
submitruns, the result is dropped. Nothing is set on an unmounted island. - Without React,
runFormSubmit(form, submitter, submit, validate)runs steps 3 to 5 and resolves to{ ok: true, result }or{ ok: false, error }. - There is no validation library. The browser's checks plus
validateare enough for a storefront form, and they keep the island small.
Newsletter: POST /api/newsletter
The storefront's newsletter endpoint takes two shapes:
| You send | It answers |
|---|---|
a JSON body { email, source? } |
200 { ok: true }, or { ok: false, code } |
a normal form post with the field email (and source) |
303 back to the same page with ?newsletter=ok, invalid or error |
The JSON code is one of:
code |
Status | Meaning |
|---|---|---|
INVALID_EMAIL |
400 | not an email address (or longer than 254 characters) |
RATE_LIMITED |
429 | too many sign-ups from this shopper's address; try later |
STORE_NOT_FOUND |
404 | the store is unknown |
STORE_UNKNOWN |
400 | the request did not come through the store's own address |
UPSTREAM_ERROR |
502 | the store's API failed or timed out |
A hidden field named bp_hp is a trap for bots. Real shoppers never see it, so it stays empty. When
it is filled, the endpoint answers success and stores nothing. source (at most 64 characters) tells
the seller where the sign-up came from, for example footer.
Use both shapes. The island sends JSON and shows the answer in place. The form keeps
action="/api/newsletter" method="post", so a shopper who submits before the island wakes up (or
without JavaScript) still signs up, and comes back to the page with ?newsletter=ok.
Create blocks/newsletter-box/newsletter-form.tsx:
'use client';
import { useForm } from '@bizzpocket/theme/client';
const MESSAGES: Record<string, string> = {
INVALID_EMAIL: 'Please check your email address.',
RATE_LIMITED: 'Too many tries. Please wait a few minutes.',
};
export function NewsletterForm({ button, returned }: { button: string; returned: string | null }) {
const { onSubmit, pending, error, done } = useForm(async (data) => {
const res = await fetch('/api/newsletter', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ email: data.get('email'), source: 'footer', bp_hp: data.get('bp_hp') }),
});
const body = (await res.json().catch(() => null)) as { ok?: boolean; code?: string } | null;
if (body?.ok !== true) throw new Error(MESSAGES[body?.code ?? ''] ?? 'We could not sign you up. Please try again.');
});
// `returned` is the `?newsletter=` of a form that posted without JavaScript.
if (done || returned === 'ok') return <p role="status">Thanks! You are on the list.</p>;
const message = error ?? (returned === 'invalid' ? MESSAGES.INVALID_EMAIL : returned === 'error' ? 'We could not sign you up. Please try again.' : null);
return (
<form action="/api/newsletter" method="post" onSubmit={onSubmit} aria-busy={pending}>
<label htmlFor="newsletter-email">Email</label>
<input
id="newsletter-email"
name="email"
type="email"
autoComplete="email"
required
aria-invalid={message !== null}
aria-describedby={message !== null ? 'newsletter-error' : undefined}
/>
<input type="hidden" name="source" value="footer" />
{/* The bot trap: off screen, out of the tab order, ignored by autofill. */}
<input name="bp_hp" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ position: 'absolute', left: '-9999px' }} />
<button type="submit" disabled={pending}>
{pending ? 'Sending...' : button}
</button>
{message !== null && (
<p id="newsletter-error" role="alert">
{message}
</p>
)}
</form>
);
}And the block, blocks/newsletter-box/newsletter-box.tsx. It reads ?newsletter= from the route, so
the result of a post without JavaScript is shown too:
import { block, f } from '@bizzpocket/theme';
import { NewsletterForm } from './newsletter-form';
export default block({
name: 'Newsletter box',
category: 'content',
fields: {
heading: f.text({ default: 'Get 10% off your first order' }),
button: f.text({ default: 'Sign me up' }),
},
render: ({ heading, button }, ctx) => (
<section>
<h2>{heading}</h2>
<NewsletterForm button={button} returned={ctx.route.filters?.newsletter ?? null} />
</section>
),
});Sign in and sign up: POST /api/customer/auth
The host's sign-in page is /account/login and its sign-up page is /account/signup. They handle
every case for you: one-time codes, magic links, Google, the captcha, merging the guest cart. A link
to them is usually the right choice. Build your own form only when the design really needs it inline
(a sign-in drawer, a sign-up step in a landing page).
The endpoint is POST /api/customer/auth?action=<action> with a JSON body. The answer is
{ success: true, data } or { success: false, error: { code, message } }. On success the host sets
the shopper's session cookie itself; your island never sees a token.
action |
Body | Notes |
|---|---|---|
login-password |
{ email_or_phone, password, store_slug } |
5 tries per 15 minutes per store and address |
signup |
{ store_slug, email or phone, password?, first_name?, last_name? } |
5 per hour per store and address. A code is sent to the email or phone. |
login-otp |
{ email_or_phone, store_slug } |
sends a one-time code |
verify-otp |
{ otp, session_token, store_slug } |
session_token is the email or phone the code was sent to |
forgot-password |
{ email_or_phone, store_slug } |
always answers that it sent, whether or not the account exists |
store_slug is required. Pass the store from render's second argument (ctx.store.slug) to the
island as a prop.
Error codes you will meet:
code |
Status | Show the shopper |
|---|---|---|
INVALID_CREDENTIALS |
401 | "That email or password is not right." |
NO_PASSWORD |
400 | the account signs in with a code: link to /account/login |
ACCOUNT_LOCKED |
423 | the message (it says how many minutes) |
ALREADY_EXISTS |
409 | "An account with this email or phone already exists." and a sign-in link |
WEAK_PASSWORD |
400 | "Use at least 10 characters." |
VALIDATION_ERROR |
400 | a field is missing or not valid |
RATE_LIMIT_EXCEEDED |
429 | the message (it says when to try again) |
CAPTCHA_REQUIRED, CAPTCHA_INVALID |
403 | link to /account/login (see the warning below) |
Warning. The host protects sign-in and sign-up with an invisible proof-of-work captcha. Its own pages solve
it; a theme island cannot. While a store runs the captcha in "enforce" mode, your own sign-in or
sign-up form is refused with CAPTCHA_REQUIRED. Always handle that code by sending the shopper to
the host's page, so the form never becomes a dead end.
A sign-in form. Create blocks/sign-in-box/sign-in-form.tsx:
'use client';
import { useForm } from '@bizzpocket/theme/client';
type AuthAnswer = { success?: boolean; error?: { code?: string; message?: string } };
const LOGIN_PAGE = '/account/login';
export function SignInForm({ storeSlug, next }: { storeSlug: string; next: string }) {
const { onSubmit, pending, error } = useForm(async (data) => {
const res = await fetch('/api/customer/auth?action=login-password', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ email_or_phone: data.get('login'), password: data.get('password'), store_slug: storeSlug }),
});
const body = (await res.json().catch(() => null)) as AuthAnswer | null;
if (body?.success !== true) {
const code = body?.error?.code;
if (code === 'CAPTCHA_REQUIRED' || code === 'CAPTCHA_INVALID' || code === 'NO_PASSWORD') {
window.location.assign(LOGIN_PAGE);
return;
}
if (code === 'INVALID_CREDENTIALS') throw new Error('That email or password is not right.');
throw new Error(body?.error?.message ?? 'We could not sign you in. Please try again.');
}
// Fold the guest cart into the shopper's cart, then load the next page as the shopper.
await fetch('/api/cart/merge', { method: 'POST' }).catch(() => {});
window.location.assign(next);
});
return (
<form onSubmit={onSubmit} aria-busy={pending} aria-describedby={error !== null ? 'sign-in-error' : undefined}>
<label htmlFor="sign-in-login">Email or phone</label>
<input id="sign-in-login" name="login" autoComplete="username" required />
<label htmlFor="sign-in-password">Password</label>
<input id="sign-in-password" name="password" type="password" autoComplete="current-password" required />
<button type="submit" disabled={pending}>
{pending ? 'Signing in...' : 'Sign in'}
</button>
{error !== null && (
<p id="sign-in-error" role="alert">
{error}
</p>
)}
<p>
<a href={LOGIN_PAGE}>Sign in with a code instead</a>
</p>
</form>
);
}And the block, blocks/sign-in-box/sign-in-box.tsx:
import { block, f } from '@bizzpocket/theme';
import { SignInForm } from './sign-in-form';
export default block({
name: 'Sign-in box',
category: 'content',
fields: {
heading: f.text({ default: 'Welcome back' }),
next: f.link({ default: '/account' }),
},
render: ({ heading, next }, ctx) => (
<section>
<h2>{heading}</h2>
<SignInForm storeSlug={ctx.store.slug} next={next ?? '/account'} />
</section>
),
});After a sign-in the island loads a new page. That is on purpose: the whole page, every island's
useCustomer() and useCart() included, then starts as the signed-in shopper.
A sign-up form with its own validation. Create blocks/sign-up-box/sign-up-form.tsx:
'use client';
import { useForm } from '@bizzpocket/theme/client';
type AuthAnswer = { success?: boolean; error?: { code?: string; message?: string } };
const MESSAGES: Record<string, string> = {
ALREADY_EXISTS: 'An account with this email already exists. Please sign in.',
WEAK_PASSWORD: 'Use at least 10 characters for your password.',
};
export function SignUpForm({ storeSlug }: { storeSlug: string }) {
const { onSubmit, pending, error, done } = useForm(
async (data) => {
const res = await fetch('/api/customer/auth?action=signup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
store_slug: storeSlug,
email: data.get('email'),
password: data.get('password'),
first_name: data.get('first_name'),
}),
});
const body = (await res.json().catch(() => null)) as AuthAnswer | null;
if (body?.success === true) return;
const code = body?.error?.code ?? '';
if (code === 'CAPTCHA_REQUIRED' || code === 'CAPTCHA_INVALID') {
window.location.assign('/account/signup');
return;
}
throw new Error(MESSAGES[code] ?? body?.error?.message ?? 'We could not create your account. Please try again.');
},
{
// Runs after the browser's own checks, before anything is sent.
validate: (data) => (data.get('password') !== data.get('confirm') ? 'The two passwords are not the same.' : undefined),
},
);
if (done) {
return (
<p role="status">
Account created. Check your email for a code, then <a href="/account/login">sign in</a>.
</p>
);
}
return (
<form onSubmit={onSubmit} aria-busy={pending}>
<label htmlFor="sign-up-name">First name</label>
<input id="sign-up-name" name="first_name" autoComplete="given-name" />
<label htmlFor="sign-up-email">Email</label>
<input id="sign-up-email" name="email" type="email" autoComplete="email" required />
<label htmlFor="sign-up-password">Password</label>
<input
id="sign-up-password"
name="password"
type="password"
autoComplete="new-password"
minLength={10}
required
aria-describedby="sign-up-hint"
/>
<p id="sign-up-hint">At least 10 characters.</p>
<label htmlFor="sign-up-confirm">Password again</label>
<input id="sign-up-confirm" name="confirm" type="password" autoComplete="new-password" required />
<button type="submit" disabled={pending}>
{pending ? 'Creating your account...' : 'Create account'}
</button>
{error !== null && <p role="alert">{error}</p>}
</form>
);
}And the block, blocks/sign-up-box/sign-up-box.tsx:
import { block, f } from '@bizzpocket/theme';
import { SignUpForm } from './sign-up-form';
export default block({
name: 'Sign-up box',
category: 'content',
fields: { heading: f.text({ default: 'Create an account' }) },
render: ({ heading }, ctx) => (
<section>
<h2>{heading}</h2>
<SignUpForm storeSlug={ctx.store.slug} />
</section>
),
});minLength={10} lets the browser catch a short password before anything is sent. The server checks it
again (WEAK_PASSWORD), as it checks every field: browser checks are for the shopper's comfort, never
for security.
Contact: no endpoint, use mailto:
The storefront host has no contact-form endpoint, and a theme has no server of its own. The
simple, honest contact form opens the shopper's mail app with the message filled in, addressed to the
store's own email (store().email, or supportEmail).
Create blocks/contact-box/contact-form.tsx:
'use client';
import { useForm } from '@bizzpocket/theme/client';
export function ContactForm({ to, storeName }: { to: string; storeName: string }) {
const { onSubmit, pending, done, reset } = useForm((data) => {
const subject = `Question for ${storeName} from ${String(data.get('name'))}`;
const body = String(data.get('message'));
window.location.href = `mailto:${encodeURIComponent(to)}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
});
if (done) {
return (
<p role="status">
Your mail app should open with the message. Not working? Write to <a href={`mailto:${to}`}>{to}</a>.{' '}
<button type="button" onClick={reset}>
Edit the message
</button>
</p>
);
}
return (
<form onSubmit={onSubmit} aria-busy={pending}>
<label htmlFor="contact-name">Your name</label>
<input id="contact-name" name="name" autoComplete="name" required />
<label htmlFor="contact-message">Message</label>
<textarea id="contact-message" name="message" required minLength={10} maxLength={2000} rows={5} />
<button type="submit">Write the email</button>
</form>
);
}And the block, blocks/contact-box/contact-box.tsx:
import { block, f, store } from '@bizzpocket/theme';
import { ContactForm } from './contact-form';
export default block({
name: 'Contact box',
category: 'content',
fields: { heading: f.text({ default: 'Contact us' }) },
data: () => ({ shop: store() }),
render: ({ heading, shop }) => {
const to = shop?.supportEmail ?? shop?.email ?? null;
// No address on file: render nothing rather than a form that cannot send.
if (shop === null || to === null) return null;
return (
<section>
<h2>{heading}</h2>
<ContactForm to={to} storeName={shop.name} />
</section>
);
},
});The store's email is already public on the storefront, so it is fine as an island prop. Never put a key for a form or mail service in a theme: island props and island code are readable by anyone. If you use an outside form service, use one that needs no secret in the browser.
Other host endpoints a theme form may use: POST /api/orders/track with { orderNumber, contact }
(order tracking for guests; contact is the order's phone or email) and
POST /api/reviews (product reviews; most themes send bizzpocket:review:submit instead, see
state.md).
Trying forms in bizzpocket dev
With --mock the dev server answers the endpoints a theme form uses, in the storefront's own
shapes. Nothing is stored, and there is no shopper account and no cart.
| Endpoint | --mock answer |
|---|---|
POST /api/newsletter |
JSON: { "ok": true }, or 400 { "ok": false, "code": "INVALID_EMAIL" }. A native form post: 303 back to the page with ?newsletter=ok or ?newsletter=invalid. |
POST /api/customer/auth?action=signup |
{ "success": true }. The email taken@example.com answers 409 ALREADY_EXISTS, to try that message. |
POST /api/customer/auth?action=login... / logout |
{ "success": true } (the page stays signed out: there are no accounts). |
/api/customer/account |
401 UNAUTHORIZED, as for a guest (the wishlist heart asks you to sign in). |
GET /api/checkout/pincode/<pin> |
Pune, Maharashtra, serviceable: true; a PIN starting with 9 is serviceable: false; a malformed one 400 INVALID_PINCODE. |
POST /api/reviews |
{ "success": true }. |
POST /api/orders/track |
404 ORDER_NOT_FOUND. |
anything else (/api/cart/...) |
404 NOT_FOUND. |
With --store only GET /api/checkout/pincode/<pin> is forwarded to the store's API (a public
read; no cookie or token goes with it). Every other endpoint answers
501 DEV_API_UNAVAILABLE. On the live storefront these endpoints act as the shopper (their session
cookie) and write into the store: a subscriber, an account, a cart, a review. A developer token lets
dev read the store's pages and catalogue; it is not allowed to act as a shopper or write, so dev
does not forward them. Try those forms with --mock, or on the store's preview.
Validation
Check in three places, from cheapest to last word:
- HTML attributes.
required,type="email",type="tel",minLength,maxLength,pattern,min,max. The browser checks them beforesubmitruns, shows its own message next to the field and focuses it. They cost no JavaScript. validate(data, form). For rules that need more than one field (two passwords that must match) or a sentence of your own. Return the message;useFormshows it aserror.- The server. It checks everything again and has the last word. Map its
codeto a sentence insubmit, and throw it.
Need a message on one field instead of one for the form? Use the browser's own: in validate, call
input.setCustomValidity('...') on form.elements, then form.reportValidity(), and return a
message. Clear it with setCustomValidity('') on the next input event, or the field stays invalid.
Error and pending UI
- While
pending: disable the submit button and change its text (Sending...), so the shopper sees the click worked.useFormalready ignores a second submit, so disabling is for clarity. Setaria-busy={pending}on the form. - On
error: show the message under the form, in an element withrole="alert", so screen readers announce it. Keep what the shopper typed:useFormnever clears the form. - On
done: replace the form with a short message in arole="status"element, or keep the form and show the message beside it. Offerreset()when sending another makes sense. - Say what to do next. "Please check your email address" helps. "Error 400" does not.
- Reserve the space for the message (or put it below the button), so the page does not jump when it appears.
Accessibility
Every form you ship must:
- Label every field with a
<label htmlFor>(oraria-labelwhen there is no room). Aplaceholderis not a label: it disappears when the shopper types. - Use the right
typeandautoComplete(email,tel,username,current-password,new-password,given-name). Phones show the right keyboard and password managers fill the fields. - Use a real
<button type="submit">inside a<form>, so Enter submits and assistive technology knows what it does. - Announce results: errors in
role="alert", success inrole="status". Link a field to its hint or error witharia-describedby, and mark it witharia-invalidwhen it is wrong. - Keep it working without JavaScript where the endpoint allows it (
actionandmethod, as in the newsletter form). An island wakes up late on a slow phone. - Keep the focus visible and the order logical. Do not remove the focus outline in your CSS.
- Hide traps properly. A honeypot field gets
tabIndex={-1},aria-hidden="true"andautoComplete="off", so neither keyboards, screen readers nor autofill reach it.
Next: images.md.