Skip to main content
中文中文View this page in Chinese.
Browse documentation

Tutorial: Your First App

Build one small app from an empty directory: create the project, add a page, an island and a form action, then build and serve it — result at every step.

Applies to v1.0.0-alpha.16 · Updated

1.0.0-alpha.16 is the current baseline for Element and Router, published to npm under the @alpha dist-tag. The steps below teach the baseline authoring surface, the one this guide documents throughout.

Before you start

You need Node.js 24.2+ and a terminal; any package manager works (npm, pnpm, yarn, or bun — this guide spells the commands as npm run …). The one bootstrap command is a plain Node invocation (ADR-0161) — no second runtime is involved, and everything after it is plain Node tooling.

The tutorial builds one app in five steps, and every step ends with something you can see:

  1. Create the project — the starter on disk, running in dev.
  2. Add a page — a new URL that answers with HTML.
  3. Add an island — one component that wakes up in the browser.
  4. Add a form action — a POST that either validates or saves and redirects.
  5. Build and serve — the dist/ artifact you deploy.

The TypeScript and TSX blocks on this page are not sketches: www#check:content compiles them with the real compiler against the framework sources — once in a local vp run site:verify, and again in the release gate (release:check's gate:release). PR CI does not run it, so a stale block is caught by the release train, not on every commit.

Step 1: Create the project

npm create @openelement my-app
cd my-app
npm run dev

The command runs on plain Node tooling: it fetches the published @openelement/create package from npm — a versionless install resolves latest, the current 1.0 line — and scaffolds the project with @openelement/* caret ranges over that release. It installs the dependencies too, so there is no separate install command.

The create CLI prints one created <path> line per file, then the handoff box naming the generator version and the next step (the box spells both commands for the package manager it detected; with --no-install it prints the install command first — for the detected manager, or npm install when none is on PATH — then the dev command):

openElement project created at ./my-app/ (template: showcase)
  initialized git repository (with .gitignore)

openElement project ready
(@openelement/create <version>)

cd my-app
npm run dev      # start the dev server

Docs: https://openelement.org

npm run dev starts the Vite dev server and prints the URL to open:

  VITE v8.1.6  ready in 412 ms

  ➜  Local:   http://localhost:5173/

That page is the starter's home route. Its layout is the whole architecture:

my-app/
  package.json      dependencies + scripts: dev, build, start, test, typecheck
  openelement.config.ts  framework options (tokens, head, shell conventions)
  vite.config.ts    Vite configuration; the plugin call takes no arguments
  app/routes/       one file per URL
  app/components/   page-scope components and their style sheets
  app/islands/      modules that opt into client delivery
  public/           static assets, copied into dist/ as-is

npm run typecheck type-checks the starter's app/ directory together with vite.config.ts and openelement.config.ts; new routes are picked up automatically.

Step 2: Add your first page

A URL is a file: app/routes/hello.tsx answers /hello. A page whose markup is static text needs only that one file — the route module exports a component and wraps it with definePage.

// app/routes/hello.tsx
import { definePage } from '@openelement/router';

export function HelloPage() {
  return (
    <main>
      <h1>Hello from a page</h1>
      <p>This markup is server-rendered HTML, with no client JavaScript.</p>
    </main>
  );
}

export default definePage(HelloPage, {
  head: {
    title: 'Hello — my-app',
    description: 'The tutorial page.',
  },
});

Two things about that module are worth knowing now:

  • It is a server function page: the compiler lowers the exported function into a generative HTML constructor, so the page renders on the server by construction — no Part Program and no property machinery, and the browser never receives the function.
  • definePage accepts only route, head, renderIntent, props and error. There is no render() field, and no route.path — the file name owns the URL.

Expected result: the dev server picks the new file up with no restart. Open http://localhost:5173/hello, or check the response:

curl -s http://localhost:5173/hello | grep -o 'Hello from a page'
Hello from a page

The heading was in the HTML the server sent — it is not injected by script. The only client module this page loads is the starter's own app-layout; the route itself adds no island.

Step 3: Add your first island

An island is a module in app/islands/. That directory is the registration surface: nothing imports it, because the build scans the directory and derives the tag from the file name (hello-counter.tsx → <hello-counter>).

app/islands/hello-counter.tsx:

import { signal } from '@openelement/element';
import { defineIslandConfig } from '@openelement/router';

export const openElement = defineIslandConfig({
  tag: 'hello-counter',
  // A shadow root is what makes the counter's markup a DSD template the browser
  // parses before any script runs.
  root: 'shadow',
  hydrate: 'idle',
  ssr: true,
  dsd: true,
});

export default function HelloCounter() {
  // The count is a signal, so the text and the two buttons read one source and
  // only the slots that read it refresh.
  const count = signal(0);

  return (
    <div class='counter-row'>
      <button type='button' onClick={() => { count.value = count.value - 1; }}>-</button>
      <span id='count'>{count.value}</span>
      <button type='button' onClick={() => { count.value = count.value + 1; }}>+</button>
    </div>
  );
}

Now host it from the page you already have. app/routes/hello.tsx becomes:

import { definePage } from '@openelement/router';
// The side-effect import is how the build learns this page reaches the island.
import '../islands/hello-counter.tsx';

export function HelloPage() {
  return (
    <main>
      <h1>Hello from a page</h1>
      <p>This markup is server-rendered HTML, with no client JavaScript.</p>
      <section class='demo'>
        <p>The server sent this counter's markup; the browser upgrades it on idle.</p>
        <hello-counter></hello-counter>
      </section>
    </main>
  );
}

export default definePage(HelloPage, { head: { title: 'Hello — my-app' } });

Expected result — reload http://localhost:5173/hello:

  • Before any JavaScript runs, the response already contains the counter's markup with 0 in it: the island rendered on the server through the same compiled component.
  • Click + and - and the number changes. hydrate: 'idle' told the browser to fetch the island's chunk once the page settled, upgrade the element, and bind the handlers the compiled component declared.
  • An island no route references is never delivered — the build derives reachable tags from your route sources, so a module parked in app/islands/ adds no JavaScript to any page.

Step 4: Add a form action

A route module can also export action. The form itself is plain HTML, so the notes page needs no client behavior and stays a server function page.

// app/routes/notes.tsx
import { definePage, fail, redirect, type OpenElementActionFailure } from '@openelement/router';

interface NotesActionData {
  error?: string;
  note?: string;
}

export function action(ctx: { formData: FormData }): OpenElementActionFailure<NotesActionData> {
  const note = String(ctx.formData.get('note') ?? '').trim();
  if (!note) {
    return fail(422, { error: 'a note is required', note });
  }
  throw redirect(`/notes?saved=${encodeURIComponent(note)}`);
}

export function NotesPage(props: { note: string; error: string; saved: string }) {
  return (
    <main>
      <h1>Notes</h1>
      <form method='post' data-open-enhance>
        <input name='note' type='text' value={props.note} placeholder='Write a note' />
        <button type='submit'>Save</button>
      </form>
      <p id='error'>{props.error}</p>
      <p id='saved'>{props.saved}</p>
    </main>
  );
}

export default definePage(NotesPage, {
  renderIntent: { mode: 'dynamic' },
  head: { title: 'Notes — my-app' },
  props({ request, actionData }) {
    const saved = request ? new URL(request.url).searchParams.get('saved') : undefined;
    const result = actionData as NotesActionData | undefined;
    return {
      note: result?.note ?? '',
      error: result?.error ?? '',
      saved: saved ?? '',
    };
  },
});

What each part does:

  • The form is plain HTML and works without JavaScript. That submission runs action on the server; fail(422, …) re-renders the same page with the message and the value the user typed.
  • redirect() answers 303 to a GET URL — post/redirect/get, so reloading the result does not re-post the form.
  • renderIntent: { mode: 'dynamic' } is deliberate here: the GET reads ?saved= from the request and must run per request. A page whose GET does not need the request can stay 'static' and still export an action; only the POST is then handled at request time.
  • props is the only seam between request scope and the compiled markup. It returns one object, and each key sets the matching declared property of the page component.

Expected result: data-open-enhance submits the form by fetch and morphs the returned document into place, so the page does not reload. To see the protocol itself, post to the action directly:

curl -i -X POST -H 'x-openelement-action: true' --data 'note=' http://localhost:5173/notes
HTTP/1.1 422 Unprocessable Entity
content-type: application/problem+json; charset=utf-8
curl -i -X POST -H 'x-openelement-action: true' --data 'note=hello' http://localhost:5173/notes
HTTP/1.1 303 See Other
location: /notes?saved=hello

Without the x-openelement-action header the same POST is an ordinary browser submission and answers HTML instead of JSON. A route can also export actions when one form needs several submit buttons, dispatched by formaction='?/name'.

Step 5: Build and serve

npm run build

The build prerenders every static route, bundles one chunk per reachable island, and — because /notes is request-time — writes the server entry too. Expected output (trimmed: the starter's own islands appear in the same table, and the per-page list is elided):

== openElement Build Manifest - Phase 3 @ 12:04:31 ==

  Client Islands:
  File                         Size
  --------------------------   --------
  ...
  hello-counter.js             …
  --------------------------   --------
  TOTAL JS                     …

  ...
  All artifacts within budget limits
ls dist

The entries this tutorial's work produced:

index.html          prerendered /
hello/index.html    prerendered /hello
client/islands/     one chunk per reachable island
island-manifests/   page-<hash>.json — which islands each page loads
server/index.js     the request-time handler: it answers POST /notes and
                    renders the styled 404 for unmatched paths

Serve the artifact:

npm start
[openElement start] request-time server entry loaded (dynamic routes enabled)
[openElement start] http://localhost:4173

The port comes from OPEN_ELEMENT_PORT, then PORT, defaulting to 4173. Verify the artifact rather than the log:

curl -i http://localhost:4173/hello | head -1
HTTP/1.1 200 OK

/hello is a file on disk; /notes reached the server entry — as does the styled 404 for an unmatched path. A project whose build has no request-time route can be served static-only with openelement start --mode=preview, which is why this one, which has one, is served with npm start.

You now have a project, a page, an island, a form action, and a build you can deploy.

Next steps

  • Routing and Data — loaders, named actions, and the two loader/action chains.
  • Islands and SSR — delivery strategies and what actually ships to the browser.
  • Deployment — the full output contract and the Nitro presets.

See also

  • Core Concepts — the component model behind the sidecar and its properties.
  • Styling — where page styles live and what crosses a shadow boundary.
  • Testing — the checks worth running against a build.