Skip to content

Progressive Enhancement

WebJs is HTML-first by design. Every page is server-rendered to real HTML. Every web component runs its render() on the server, so the component's initial markup is in the response before any script loads. With JavaScript disabled (slow networks, strict CSP, hostile proxies, user preference, ad-blockers, hydration races) the page still paints, content reads, links navigate, and forms submit.

JavaScript is opt-in per interactive behavior, not per component. A counter custom element renders as "0" on the server, and only the +/- click handling needs JS. A dropdown renders its trigger and closed state on the server, and only the open/close toggle needs JS. The HTML is the floor, and @click, signal mutations, and the client router are layered on top.

What works without JavaScript

  • Page rendering. Every page.ts runs on the server and emits HTML. Layouts, metadata, OG tags, the page body all arrive in the first response.
  • Custom elements' initial markup. Every web component's render() runs server-side. Light-DOM components serialize as direct children, and shadow-DOM components emit Declarative Shadow DOM so scoped styles paint before JS loads.
  • Navigation. <a href="..."> is a real link. The client router enhances it into a partial-swap when JS is active. With JS off, the browser performs a standard navigation.
  • Form submissions (write-paths). A server action binds straight into the form and submits as a plain HTML POST:
    <form action=${createPost}>
      <input name="title">
      <textarea name="body"></textarea>
      <button type="submit">Save</button>
    </form>
    Submitting this form works whether or not JavaScript is enabled. The client router upgrades it to a partial-swap submission when active.
  • CSS-driven interactivity. Hover, focus, :checked, :target, <details>/<summary>, native dropdowns (<select>) all work without JS by construction.
  • Suspense fallbacks. The fallback HTML is in the first chunk of the response. Without JS, the user sees the fallback content and won't see streamed-in updates, but the page is never blank.
  • Streaming-injected modulepreload hints. The server emits <link rel="modulepreload"> for every module the page needs. With JS off, those preloads are simply ignored.

What needs JavaScript

Only behaviors that respond to user input or update state in place:

  • @click / @input / @change handlers on custom elements. The button is in the HTML, the handler isn't.
  • Signal updates and reactive re-renders. A counter starts at its server-rendered value; counting up calls signal.set(), which the component's built-in SignalWatcher picks up and re-renders.
  • Client-router partial-swap navigation. With JS off, links still navigate, they just trigger a full-page load instead of a swap. UX degrades to the standard browser experience.
  • Suspense streaming. The fallback paints without JS, but streamed-in updates need scripts to be applied.
  • WebSockets. No fallback; if you need realtime, you need JS.

Notice the asymmetry: showing things works without JS, while reacting to user input or external events requires it. This is the right asymmetry for the web platform.

Server-only markup ships zero JavaScript

WebJs takes the asymmetry one step further. A page, layout, loading template or boundary runs only on the server, like a Next.js server component, and never loads in the browser: the boot imports the components it renders and nothing else. A route that renders no interactive component therefore ships zero application JavaScript and is pure server-rendered HTML. It still navigates and submits forms through native browser behavior, which is exactly the progressive-enhancement baseline, and the client router rides along automatically as soon as any component loads @webjsdev/core.

So a page can import a .server.ts utility, a database client or a node: module freely, and anything that needs a browser belongs in a component. Every component in an ordinary file ships, as in Lit. Markup that only displays server data and never needs the browser is written as a server-only component (a WebComponent in a *.server.ts file) or a function returning html, and neither ships. webjs check refuses the shapes that would silently do nothing (a component class defined in a page, an @click on a page's template, interactivity inside a .server component), and webjs status warns about browser-looking code in a page. The quick check: page.ts / layout.ts never appear in the browser's network tab. See What Ships to the Browser.

It is the no-build framework's answer to dead-JavaScript-on-the-wire elimination, the one benefit React Server Components offer that a progressive-enhancement framework would otherwise lack, achieved here without a bundler or a Flight protocol: where code runs is decided by where you put it (see Architecture).

// components/status-badge.server.ts: server-only, the browser never downloads it.
class Badge extends WebComponent {
  render() { return html`<span class="badge">verified</span>`; }
}
Badge.register('status-badge');

// components/my-counter.ts: an ordinary component, so its JS ships and hydrates.
class Counter extends WebComponent {
  render() { return html`<button @click=${() => this.inc()}>+</button>`; }
}
Counter.register('my-counter');

Where your npm packages run

An npm package reaches the browser when a module that loads on the client imports it (the boot script loads the components a page renders and instrumentation-client.ts, never the page or layout itself; loading a module runs its import statements). So:

  • Server-only dependency (a date library you only use during SSR): use it in the page, layout or a .server.{js,ts} file, none of which ever loads in the browser. A server-only component (in a *.server.ts file) may import it too.
  • Client-only package (analytics, a polyfill): import it from instrumentation-client.ts for the whole app, or from the component that needs it. A side-effect import in a page or layout runs only on the server, so it never reaches the browser (webjs doctor warns about one). You do not need a 'use client'-style annotation, the import in a module the browser loads is the signal.

The distinction is where the importing module runs, not whether it imports an npm package. A package used inside a page's body or a server-only component never executes on the client, and one an ordinary component imports always does.

The design rules

Build features so the first paint is the right content, and JavaScript only adds reactivity on top.

1. Use real <a> for navigation

Don't write JS-only click handlers for routing.

// ✅ works without JS, and the router enhances it
<a href="/posts/${post.id}">${post.title}</a>

// ❌ requires JS to navigate
<button @click=${() => router.push(`/posts/${post.id}`)}>
  ${post.title}
</button>

2. Use <form action=${importedAction}> for writes

Bind a 'use server' action into the form and that is the whole wiring. The renderer omits the action attribute so the form posts to the page's own URL, supplies method="post" and an enctype, and emits a hidden field carrying the action's identity. The submission runs the action, which returns an ActionResult. It works as a plain HTML POST when JS is off, and as a partial-swap submission when JS is on. One piece of code covers both ends of the spectrum, and no form library is involved.

The action validates on the server, then returns one of two outcomes. A success result is a 303 See Other to result.redirect (Post/Redirect/Get). A failure result re-SSRs the same page at 422 with the result on ctx.actionData, so the page repopulates the fields from actionData.values and shows the messages from actionData.fieldErrors.

// modules/posts/actions/create-post.server.ts
'use server';
// A form-bound action receives the submitted fields as one object, read by
// property (input.get('title') works too).
export async function createPost(input: { title?: string; body?: string }) {
  const title = String(input.title || '').trim();
  const body = String(input.body || '').trim();
  const values = { title, body };
  if (!title) {
    return { success: false, fieldErrors: { title: 'Title is required' }, values, status: 422 };
  }
  const post = await db.insert(posts).values({ title, body }).returning();
  return { success: true, redirect: `/posts/${post[0].id}` };
}

// app/posts/page.ts
import { html } from '@webjsdev/core';
import { createPost } from '#modules/posts/actions/create-post.server.ts';

export default function NewPost({ actionData }: {
  actionData?: { fieldErrors?: Record<string, string>; values?: Record<string, string> };
}) {
  const errors = actionData?.fieldErrors || {};
  const values = actionData?.values || {};
  return html`
    <form action=${createPost}>
      <input name="title" value=${values.title || ''} required>
      ${errors.title ? html`<p class="error">${errors.title}</p>` : ''}
      <textarea name="body" required>${values.body || ''}</textarea>
      <button type="submit">Publish</button>
    </form>
  `;
}

With JS off the browser submits, follows the 303, or renders the 422. With JS on the client router posts the same body to the same URL, applies the 422 in place (no reload, and what was typed is put back into every control the re-render did not explicitly set) and follows the 303 via fetch, updating a page it lands back on in place (no new history entry, scroll and focus kept, the form reset on success), so the two paths are identical by construction rather than by two implementations agreeing. Both are Origin-verified, so a no-JS form needs no CSRF token field. Avoid the pattern of fetch('/api/...') + a click handler for write-paths. That's JS-required by construction.

A form that binds nothing gets a 405: there is no page action export to catch a bare <form method="post">. The quieter half of that is worth knowing too. A form with no method at all submits as a GET, so there is no body and no 405; the page simply re-renders with a 200. Multi-submitter forms can bind per-button actions using formaction=${action} on submitter buttons inside a bound form, which work with JavaScript disabled via standard DOM submitter precedence.

A per-button action is self-sufficient. The renderer supplies the submission attributes at the level where the action is bound, so a formaction=${action} button gains formmethod="post" and formenctype ON THE BUTTON, alongside the identity riding its own name/value pair. A submitter's formmethod overrides the form's method per HTML, so the button posts correctly inside a bound form, an unbound form, a form with no method, or a method="get" form. That is what makes a submitter inside a component safe: the component renders its own template in a separate pass with no view of the host page, and it no longer needs one. Bind the enclosing form when the FORM itself should run an action on a plain submit.

"Identical by construction" is a claim about the whole submission, encoding included, and it is enforced in two places. The router resolves the effective enctype with native precedence (a submitter's formenctype over the form's, decided on whether the attribute is PRESENT rather than on its value being non-empty, so formenctype="" means urlencoded and not the form's declared encoding) and ENCODES the body accordingly: multipart/form-data sends FormData, and application/x-www-form-urlencoded, which is the HTML default and therefore what a plain <form method="post"> means, sends URLSearchParams. Before that the router built FormData for everything, so an ordinary POST form sent a urlencoded body without JS and a multipart body with it. A text/plain POST is the one encoding the server cannot parse, so the router declines it and lets the browser submit natively, which makes both paths do the same thing rather than one of them appear to work.

A submitter that BINDS its own action is refused when it also declares a formmethod other than post, an unparseable formenctype, or formmethod="dialog", because those contradict the action attached to that same button. A button that binds nothing is left alone: its formmethod / formenctype is a legal native override, the author wrote it deliberately, and the form's action simply does not run, exactly as the same markup behaves anywhere else. In dev the client logs a console error at submit time when a submission is carrying an identity it cannot deliver.

3. Make components render correctly on the server

The component's render() output must be the right HTML, not a placeholder waiting for hydration. Bad:

// ❌ first paint is empty, relies on hydration
class PostList extends WebComponent {
  posts = [];
  render() { return html`<ul>${this.posts.map(...)}</ul>`; }
  async firstUpdated() {
    this.posts = await fetchPosts();   // ← only runs in browser
    this.requestUpdate();
  }
}

Good. Fetch on the server, render with real data, no client roundtrip:

// ✅ first paint has the data
// app/posts/page.ts
import { listPosts } from '#modules/posts/queries/list-posts.server.ts';
export default async function Posts() {
  const posts = await listPosts();
  return html`<post-list .posts=${posts}></post-list>`;
}

4. Don't gate read-paths on hydration

Static content (text, images, links, lists, marketing sections, layouts) should be plain HTML or a function returning an html`` template, not a custom element. Custom elements are for when you need state or lifecycle. If your component has no @click, no signal mutation, and no firstUpdated() doing anything, it should probably be a plain function.

5. Use <form>'s built-in validation before reaching for JS

required, pattern, min/max, type="email", type="url" are all enforced by the browser without JS. Add custom JS validation only when these aren't enough.

6. Set SSR-meaningful defaults in the constructor, not connectedCallback

The SSR pipeline constructs each web component (new Cls()), applies its attributes, runs willUpdate and controllers' hostUpdate, reflects reflect: true properties, and calls render(). It does not call connectedCallback, firstUpdated, updated, or any browser-only hook. Those run only in the browser, after the script loads. Whatever state your component should display on first paint must be set in the constructor, derived in willUpdate, or be derivable from the factory's reactive properties on the element's attributes.

// ❌ first paint is empty, initial state set in browser-only hook
class Cart extends WebComponent({ items: prop<Item[]>(Array) }) {
  connectedCallback() {                       // ← server never runs this
    super.connectedCallback();
    this.items = readFromLocalStorage();
    this.requestUpdate();
  }

  render() { return html`<ul>${this.items.map(...)}</ul>`; }
}
// ✅ SSR-safe: sensible default in the constructor, browser hook
//    refines it after hydration
class Cart extends WebComponent {
  items = signal<Item[]>([]);                  // ← SSR uses this

  connectedCallback() {
    super.connectedCallback();
    const stored = readFromLocalStorage();
    if (stored) this.items.set(stored);         // browser-only refinement
  }

  render() { return html`<ul>${this.items.get().map(...)}</ul>`; }
}

For data that genuinely can't be known on the server (a user's localStorage, viewport size, online status, time zone, theme preference), one of three patterns works:

  • Sensible default + browser refinement. The instance signal's initial value ([], 'system', empty) is what SSR renders. connectedCallback reads the browser-only source and writes the signal. Accept that the first paint may flash from the default to the real value once JS arrives. Often fine.
  • Synchronous bootstrap script. If the flash is unacceptable (theme color, RTL direction), emit a tiny inline <script> in the layout's <head> that reads localStorage and writes the value to document.documentElement (e.g. data-theme attribute). CSS reads from that attribute, so the page renders with the correct value before the component upgrades. This is how <theme-toggle> works in this docs site.
  • Send it from the server. If the data is available via a cookie or the request (session, accept-language), read it in the page function and pass it as an attribute or property on the component. The SSR pipeline applies attributes before render(), so the first paint has the right value.

Testing: run with JavaScript disabled

Before marking a feature done, exercise the user's read + write paths with JS turned off. In Chrome DevTools: Settings → Debugger → "Disable JavaScript". Then:

  • Reload the page. Content should paint. Look for an empty container, a stuck loading skeleton, or a JS-rendered widget showing nothing. Those indicate a hydration-dependent first paint.
  • Navigate via the page's links. Each should produce a full page load that lands on the right URL.
  • Submit each form. Each should POST to its own page URL and render the resulting page.
  • Interactive widgets (counters, dropdowns) won't react. That's expected and fine. The widget's initial state should still be visible.

A green run here means your feature degrades correctly. Your users on flaky networks, strict CSP, and Chrome's "data saver" mode will thank you.

Why this matters

  • Resilience. Scripts can fail to load, be blocked, or hang. Networks drop. Edges return JS-stripped HTML through aggressive CDN transforms. With HTML-first, your page survives all of it.
  • Performance. Time-to-first-content is determined by HTML, not by waiting for a JS bundle to parse and execute. Even with JS available, the user reads earlier.
  • SEO and link previews. Crawlers and link-preview generators see real content, not a JS shell. Open Graph, Twitter cards, Discord embeds all just work.
  • Accessibility. Real <a> and real <form> elements come with keyboard, screen-reader, and assistive-tech support out of the box. Reinvented JS-only equivalents almost never do.
  • Composability. Server actions can be called via RPC and via plain HTML forms with the same code. Routes work via the client router and via plain browser navigation with the same URLs. One implementation, two ends of the progressive-enhancement spectrum.

Progressive enhancement isn't a feature you enable in WebJs. It's the architecture. Architecture walks through how the request lifecycle produces HTML-first responses. Server Actions shows the form-first pattern. Client Router shows how the SPA-style transitions enhance plain links and forms.