BizzPocket

Newsletter signup

An email signup with useForm that posts to the storefront's own /api/newsletter route, shows the result in place, and still works without JavaScript.

On this page

Goal: an email signup that puts the shopper on the store's Subscribers list, says "Thanks" (or why it failed) without reloading the page, and still works as a plain form before its JavaScript arrives.

Data none
JavaScript one island, about 1.5 KB gzip
Uses useForm(), the storefront route POST /api/newsletter, ctx.route.filters

The block has three files.

The endpoint

The storefront host has one signup route, POST /api/newsletter. It adds the store (from the address the shopper is on) and the shopper's IP, and passes the signup to BizzPocket, which validates the address, stores it once and rate-limits per IP. It accepts two shapes:

Request Answer
JSON: { "email": "...", "source"?: "...", "bp_hp"?: "" } { "ok": true }, or { "ok": false, "code": "..." } with INVALID_EMAIL (400), RATE_LIMITED (429), STORE_NOT_FOUND (404), UPSTREAM_ERROR (502) or STORE_UNKNOWN (400)
a normal form post (email, source, bp_hp fields) 303 back to the page the form was on, with ?newsletter=ok, ?newsletter=invalid or ?newsletter=error added
  • source (at most 64 characters) is shown in the seller's Subscribers list as where the signup came from.
  • bp_hp is a honeypot: a request that fills it gets ok and nothing is stored.

The island below uses the JSON shape. The form's own action uses the second, for shoppers whose JavaScript has not loaded.

The island

Create blocks/newsletter/signup-form.tsx:

blocks/newsletter/signup-form.tsx
'use client';
import { useForm } from '@bizzpocket/theme/client';

/** The storefront's own route. It adds the store and the shopper's IP, and owns the real validation. */
const ENDPOINT = '/api/newsletter';

/** What the route answers a JSON request with. */
type Answer = { ok: true } | { ok: false; code?: string };

const MESSAGES: Record<string, string> = {
  INVALID_EMAIL: 'That email address does not look right.',
  RATE_LIMITED: 'Too many tries. Please wait a minute and try again.',
};
const FALLBACK = 'We could not sign you up just now. Please try again.';

export interface SignupFormProps {
  formId: string;
  placeholder: string;
  button: string;
  thanks: string;
  /** `?newsletter=` after a sign-up sent without JavaScript: `ok`, `invalid` or `error`. */
  status: string | null;
}

export function SignupForm({ formId, placeholder, button, thanks, status }: SignupFormProps) {
  const { onSubmit, pending, error, done } = useForm(
    async (data) => {
      const res = await fetch(ENDPOINT, {
        method: 'POST',
        headers: { 'content-type': 'application/json', accept: 'application/json' },
        body: JSON.stringify({
          email: String(data.get('email') ?? '').trim(),
          source: 'newsletter',
          bp_hp: String(data.get('bp_hp') ?? ''),
        }),
      }).catch(() => null); // offline: show our own message, not the browser's
      const answer = (await res?.json().catch(() => null)) as Answer | null | undefined;
      if (answer?.ok === true) return;
      const code = answer && !answer.ok ? answer.code : undefined;
      // useForm shows the message of what `submit` throws.
      throw new Error((code !== undefined && MESSAGES[code]) || FALLBACK);
    },
    {
      // The browser has already checked `required` and `type="email"`; this catches a common slip.
      validate: (data) => (/@(gmial|gamil|gmai)\.com$/i.test(String(data.get('email'))) ? 'Did you mean gmail.com?' : undefined),
    },
  );

  if (done || status === 'ok') {
    return (
      <p className="nl-done" role="status">
        {thanks}
      </p>
    );
  }
  const shown = error ?? (status === 'invalid' ? MESSAGES.INVALID_EMAIL! : status === 'error' ? FALLBACK : null);

  return (
    // `action` and `method` let the form post the old way before the island wakes up.
    <form className="nl-form" action={ENDPOINT} method="post" onSubmit={onSubmit}>
      <label className="nl-sr" htmlFor={`${formId}-email`}>
        Email address
      </label>
      <input
        id={`${formId}-email`}
        className="nl-input"
        name="email"
        type="email"
        required
        maxLength={254}
        autoComplete="email"
        inputMode="email"
        spellCheck={false}
        placeholder={placeholder}
        aria-invalid={shown !== null}
        aria-describedby={`${formId}-msg`}
      />
      <button className="nl-button" type="submit" disabled={pending}>
        {pending ? 'Signing you up...' : button}
      </button>
      <input type="hidden" name="source" value="newsletter" />
      {/* A trap for bots: hidden from people, and the route quietly ignores a filled one. */}
      <div className="nl-trap" aria-hidden="true">
        <label>
          Leave this empty
          <input type="text" name="bp_hp" tabIndex={-1} autoComplete="off" defaultValue="" />
        </label>
      </div>
      <p id={`${formId}-msg`} className="nl-msg" role="alert">
        {shown}
      </p>
    </form>
  );
}

The block

Create blocks/newsletter/newsletter.tsx:

blocks/newsletter/newsletter.tsx
import { block, f } from '@bizzpocket/theme';
import { SignupForm } from './signup-form';
import './newsletter.css';

export default block({
  name: 'Newsletter',
  category: 'promo',
  fields: {
    heading: f.text({ default: 'Get new arrivals first' }),
    text: f.text({ multiline: true, default: 'One email a month. No spam, and you can leave any time.' }),
    placeholder: f.text({ default: 'you@email.com' }),
    button: f.text({ default: 'Sign me up' }),
    thanks: f.text({ default: 'Thanks! You are on the list.' }),
  },
  render: ({ heading, text, placeholder, button, thanks }, ctx) => (
    <section className="nl" aria-labelledby={`nl-${ctx.blockId}-title`}>
      <h2 id={`nl-${ctx.blockId}-title`} className="nl-title">
        {heading}
      </h2>
      {text ? <p className="nl-text">{text}</p> : null}
      <SignupForm
        formId={`nl-${ctx.blockId}`}
        placeholder={placeholder}
        button={button}
        thanks={thanks}
        status={ctx.route.filters?.newsletter ?? null}
      />
    </section>
  ),
});

The CSS

Create blocks/newsletter/newsletter.css:

blocks/newsletter/newsletter.css
.nl { padding: 3rem 1rem; text-align: center; background: #f6f6f4; }
.nl-title { margin: 0 0 0.5rem; }
.nl-text { margin: 0 auto 1.5rem; max-width: 32rem; opacity: 0.8; }
.nl-form { display: flex; flex-wrap: wrap; justify-content: center; gap: 0.5rem; max-width: 30rem; margin: 0 auto; }
.nl-input { flex: 1 1 14rem; padding: 0.75rem 1rem; border: 1px solid #ccc; border-radius: 999px; font: inherit; }
.nl-input[aria-invalid='true'] { border-color: #b91c1c; }
.nl-button { padding: 0.75rem 1.5rem; border: 0; border-radius: 999px; background: #111; color: #fff; font-weight: 600; cursor: pointer; }
.nl-button:disabled { opacity: 0.6; cursor: progress; }
.nl-msg { flex-basis: 100%; min-height: 1.25rem; margin: 0.25rem 0 0; color: #b91c1c; font-size: 0.9rem; }
.nl-done { font-weight: 600; }
.nl-sr, .nl-trap { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }

Put it in the footer region of layouts/global.json ("type": "newsletter") or on the home page with bunx bizzpocket add-to-layout newsletter.

Note. bizzpocket dev --mock answers /api/newsletter with the storefront's answers (a valid email is ok, anything else INVALID_EMAIL) and stores nothing, so both states can be tried. dev --store does not forward it (it would add a real subscriber) and answers 501 DEV_API_UNAVAILABLE, so a signup there shows "We could not sign you up just now". You can also open the page with ?newsletter=ok or ?newsletter=invalid to see the two states (forms.md).

How it works

  • useForm runs the submit. It stops the page from reloading, lets the browser check required and type="email" (and show its own message), then runs validate, then submit. pending disables the button and ignores a second press, done swaps the form for the thanks line, and whatever submit throws becomes error.
  • JSON in, JSON out. submit posts { email, source, bp_hp } as JSON, so the route answers { ok, code } instead of redirecting. Known codes get their own sentence, everything else (including no network) the fallback. The route and BizzPocket own the real validation; the browser checks are there to save the shopper a round trip.
  • It works before JavaScript. The form also has action="/api/newsletter" and method="post". A shopper who submits before the island wakes gets the route's 303 back to the same page with ?newsletter=ok|invalid|error. That value reaches the block as ctx.route.filters.newsletter, which it passes to the island as status, so the result shows on the server-rendered page.
  • Accessible messages. The input has a real (visually hidden) label, aria-invalid and aria-describedby pointing at the message, which is a role="alert" region. The ids use ctx.blockId, so two signup blocks on one page do not clash.
  • The honeypot. bp_hp is hidden from people and from the keyboard (tabIndex={-1}), and named so address autofill leaves it alone. A bot that fills it is told "ok" and nothing is stored.

JS cost

block       server B  client gz  css gz  data
----------  --------  ---------  ------  ----
newsletter      1092       1464     438  none

About 1.5 KB gzip, useForm included. The block keeps the default hydrate: 'visible': a signup usually sits low on the page, so the island costs nothing until the shopper scrolls near it. On the Bun host, the first island on a page also loads the shared React runtime, once for every island on the page.

For no JavaScript at all, drop the island and render the same <form method="post" action="/api/newsletter"> from the block, with the status line read from ctx.route.filters.newsletter. Every signup then reloads the page.

Limits

  • The storefront host checks signups for bots with a proof-of-work token that it adds to a plain form submit. An island that sends the request itself, as here, does not get that token, and there is no client helper to ask for one. BizzPocket accepts signups without it today.