BizzPocket

Delivery check by PIN code

A "Do you deliver to my PIN code?" box for the product page, built on the storefront's own PIN code lookup, with its limits stated plainly.

On this page

Goal: a small form on the product page: the shopper types a 6-digit PIN code and sees the town and whether the store delivers there.

Read this first: what exists today.

  • There is no PIN code or serviceability operation in BROWSER_QUERY_OPS, so useQuery() cannot do this, and neither can data() or load().
  • The store's API has a lookup, GET /storefront/<store>/pincode/<pin>, used by checkout for address autofill. The Next storefront host serves it on the shop's own address as GET /api/checkout/pincode/<pin>. This recipe calls that route from an island with useForm().
  • The Bun runtime that serves themes has no such route. There the request gets no JSON, and the island shows a "check at checkout" message instead. bizzpocket dev answers it: with --mock a sample city (a PIN starting with 9 is not delivered), with --store the store's real lookup (forms.md).
  • The answer is a hint, not a promise: it is worked out for a nominal 0.5 kg parcel with no cart, and it can be "unknown". The shipping quote at checkout is the authority.

The island

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

/** What `GET /api/checkout/pincode/<pin>` answers, inside `{ success: true, data }`. */
type Lookup = {
  pincode: string;
  city: string;
  state: string;
  /** Absent when the store could not tell: "unknown", never "no". */
  serviceable?: boolean;
};

type Envelope = { success?: boolean; data?: Lookup; error?: { code?: string; message?: string } };

const UNAVAILABLE = 'We could not check right now. Your delivery options are shown at checkout.';

async function lookUp(pin: string): Promise<Lookup> {
  let res: Response;
  try {
    res = await fetch(`/api/checkout/pincode/${encodeURIComponent(pin)}`, { headers: { accept: 'application/json' } });
  } catch {
    throw new Error(UNAVAILABLE);
  }
  // A host without the route answers with a page, not JSON.
  const body = (await res.json().catch(() => null)) as Envelope | null;
  if (body === null) throw new Error(UNAVAILABLE);
  if (res.ok && body.success !== false && body.data) return body.data;
  // INVALID_PINCODE (400) and PINCODE_NOT_FOUND (404) carry a sentence for the shopper.
  const code = body.error?.code;
  if ((code === 'INVALID_PINCODE' || code === 'PINCODE_NOT_FOUND') && body.error?.message) throw new Error(body.error.message);
  if (res.status === 429) throw new Error('Too many checks. Please wait a minute and try again.');
  throw new Error(UNAVAILABLE);
}

export function DeliveryForm({ label, button, yes, no, unknown }: { label: string; button: string; yes: string; no: string; unknown: string }) {
  const { onSubmit, pending, error, done, result, reset } = useForm((data) => lookUp(String(data.get('pin')).trim()));

  return (
    <div className="dc">
      <form className="dc__form" onSubmit={onSubmit}>
        <label className="dc__label" htmlFor="dc-pin">
          {label}
        </label>
        <div className="dc__row">
          <input
            id="dc-pin"
            className="dc__input"
            name="pin"
            inputMode="numeric"
            autoComplete="postal-code"
            required
            pattern="[1-9][0-9]{5}"
            maxLength={6}
            title="A 6-digit PIN code"
            onInput={done ? reset : undefined}
          />
          <button className="dc__button" type="submit" disabled={pending}>
            {pending ? 'Checking...' : button}
          </button>
        </div>
      </form>
      {/* Always in the page, so the answer appearing does not push the content below. */}
      <p className="dc__answer" role="status" aria-live="polite">
        {error !== null
          ? error
          : done && result
            ? `${result.city}, ${result.state}: ${result.serviceable === true ? yes : result.serviceable === false ? no : unknown}`
            : ''}
      </p>
    </div>
  );
}

The block

blocks/delivery-check/delivery-check.tsx
import { block, f } from '@bizzpocket/theme';
import { DeliveryForm } from './delivery-form';
import './delivery-check.css';

export default block({
  name: 'Delivery check',
  category: 'commerce',
  description: 'Shoppers enter their PIN code to see whether you deliver there.',
  fields: {
    label: f.text({ default: 'Check delivery to your PIN code' }),
    button: f.text({ default: 'Check' }),
    yes: f.text({ default: 'we deliver here.' }),
    no: f.text({ default: 'sorry, we do not deliver here yet.' }),
    unknown: f.text({ default: 'you will see delivery options at checkout.' }),
  },
  render: ({ label, button, yes, no, unknown }) => (
    <DeliveryForm label={label} button={button} yes={yes} no={no} unknown={unknown} />
  ),
});
blocks/delivery-check/delivery-check.css
[data-theme] .dc__label {
  display: block;
  margin-bottom: 0.375rem;
  font-weight: 600;
}
[data-theme] .dc__row {
  display: flex;
  gap: 0.5rem;
  max-width: 22rem;
}
[data-theme] .dc__input {
  flex: 1 1 auto;
  min-width: 0;
  padding: 0.625rem 0.75rem;
  border: 1px solid var(--color-border, rgba(0, 0, 0, 0.2));
  border-radius: var(--radius-input, 0.5rem);
  font: inherit;
  letter-spacing: 0.1em;
}
[data-theme] .dc__button {
  padding: 0.625rem 1rem;
  border: 0;
  border-radius: var(--radius-button, 0.5rem);
  background: var(--color-primary, #111);
  color: var(--color-on-primary, #fff);
  font: inherit;
  cursor: pointer;
}
[data-theme] .dc__button:disabled {
  opacity: 0.6;
}
/* One line reserved for the answer: no jump when it appears. */
[data-theme] .dc__answer {
  min-height: 1.5em;
  margin: 0.5rem 0 0;
  font-size: 0.875rem;
}

Put it on the product page, under the buy box: bizzpocket add-to-layout delivery-check --page product (or add it in the editor).


How it works

  • useForm() runs the submit. The browser checks required and pattern first (a PIN starts with 1 to 9 and has six digits, the same rule the server uses), then lookUp runs. A thrown Error becomes error; the returned lookup becomes result with done set.
  • The route. /api/checkout/pincode/<pin> is on the shop's own address, so there is no CORS and no API host to configure. The Next host refuses a malformed PIN itself, forwards the rest to the store's API without the shopper's cookies, and lets the answer be cached for a day.
  • Three answers, not two. serviceable: true and false are the store's delivery rules for that PIN code. When the shipping setup could not answer, serviceable is left out, and the island says "you will see delivery options at checkout" rather than "no".
  • Errors. An unknown PIN (PINCODE_NOT_FOUND) and a malformed one (INVALID_PINCODE) show the server's sentence. The API allows 30 checks a minute per store and visitor; past that it answers 429. Anything else, including a host without the route, shows the "check at checkout" message.
  • No layout shift. The answer line is always rendered and has a fixed minimum height.
  • Before the island wakes up (hydrate is the default 'visible'), a submit is a normal form submit to the current page, which only reloads it with ?pin=. Set hydrate: 'load' on the block if it sits above the fold.

JS cost

One island: about 1.3 KB gzip in the client gz column (the island, useForm and the fetch; React is shared by every island on the page). Nothing loads until the block comes near the screen. CSS is about 0.3 KB gzip.

What is missing in the SDK

  • A browser operation for this (a pincodeLookup in BROWSER_QUERY_OPS) would make it work on every host, bizzpocket dev included, and through useQuery() with its cache.
  • There is no per-product or per-cart check: the answer does not know the item's weight, size or the seller's stock location.

See also