# A form as an Astro island

URL: https://docs.forms.saastro.io/docs/recipes/astro-island
> Render a Hub-served form from an Astro page with the schema fetched on the server, so the first HTML already contains the form and nothing is requested on load.

# A form as an Astro island

## What it combines

- **`<HubForm>`** — fetches a form schema from the Saastro ingestion endpoint and submits back to it
- **`initialSchema`** — a schema the host already fetched, so the first render is the form and not a "Loading…" placeholder
- **An Astro island** — a React component hydrated on the client with `client:load` (or `client:visible`)

```tsx
import { FormBuilder, HubForm } from '@saastro/forms';

/**
 * What `https://submit.saastro.io/v1/<siteId>/<formSlug>.json` returns: a plain,
 * serialisable form config. In a real page you fetch it in the `.astro`
 * frontmatter (see index.mdx); here it is built locally so the demo needs no network.
 */
export function createSchema() {
  const config = FormBuilder.create('newsletter')
    .layout('manual')
    .columns(12)
    .addField('email', (f) =>
      f.type('email').label('Email').required().email().columns({ default: 12 }),
    )
    .addField('topic', (f) =>
      f
        .type('select')
        .label('Topic')
        .required()
        .options([
          { value: 'product', label: 'Product news' },
          { value: 'engineering', label: 'Engineering' },
        ])
        .columns({ default: 12 }),
    )
    .addStep('subscribe', ['email', 'topic'])
    .initialStep('subscribe')
    .build();
  // The Hub serves JSON: drop anything a JSON round trip would lose.
  return JSON.parse(JSON.stringify(config)) as unknown;
}

/**
 * The island. Astro hydrates it on the client; because `initialSchema` is set,
 * the very first render (and the server-rendered HTML) already contains the form
 * and no schema request is made.
 */
export function NewsletterIsland({
  schema,
  hubUrl,
  components,
}: {
  schema: unknown;
  hubUrl?: string;
  /** Primitive UI components. Functions cannot cross an island boundary as props: import them here. */
  components?: Record<string, unknown>;
}) {
  return (
    <HubForm
      siteId="my-site"
      formSlug="newsletter"
      hubUrl={hubUrl}
      initialSchema={schema}
      formProps={components ? { components: components as never } : undefined}
    />
  );
}
```

## The code

The **Code** tab above has the island (`NewsletterIsland`) and a local `createSchema()` that stands in for the Hub's JSON. In a real Astro page you fetch the schema in the frontmatter, which runs on the server for every request:

```astro
---
// src/pages/newsletter.astro
import { NewsletterIsland } from '../components/NewsletterIsland';

const res = await fetch('https://submit.saastro.io/v1/my-site/newsletter.json');
// `null` means "the host tried and failed": the island falls back to fetching on the client.
const schema = res.ok ? await res.json() : null;
---

<NewsletterIsland client:load schema={schema} />
```

## How it works

- **Server render** — `<HubForm>` fetches inside an effect, and effects do not run during server rendering. Without `initialSchema` the HTML would contain only the loading fallback. With it, the first render is already `ready`, so the form is in the HTML and hydration only attaches handlers.
- **No request on load** — when `initialSchema` is present no schema `GET` is issued. `siteId`, `formSlug` and `hubUrl` are then used only to build the submit handler.
- **Same checks** — the schema still goes through the renderable check: one without fields or steps shows the "unconfigured" banner.
- **Submit** — the form posts to `<hubUrl>/<siteId>/<formSlug>/submit` and shows the success panel when the response is `{ ok: true }`.

## Caveats

- **Components cannot be props** — Astro serialises island props, and functions and components don't survive that. Import your UI primitives inside the island file (or wrap it in a provider there) and pass only data from the `.astro` file.
- **Schema must be JSON** — pass what the endpoint returned, not a config built with Zod schemas or handlers.
- **Hydration directive** — `client:load` hydrates immediately; `client:visible` waits until the form is on screen, and until then the server-rendered form is not interactive.
- **Failed fetch** — pass `null` so the island retries from the browser, and keep an `errorFallback` for when that fails too.

## Variations

- Use `client:only="react"` if you do not need the server-rendered HTML; then `initialSchema` is optional.
- Add `plugins={[localStoragePlugin]}` to `<HubForm>` to resume a half-filled form — see [Save and continue later](/docs/recipes/save-and-continue).
- Set `locale` to the page language to render a translated form.

## Related

- [Save and continue later](/docs/recipes/save-and-continue)
- [Using @saastro/forms without Vite](/docs/recipes/nextjs-without-vite)
- [i18n](/docs/i18n)
