Server Rendering
Render pages on the server for instant loads and SEO.
Server modules can be written with JSX, h() or both
what-compiler has a server target: when Vite transforms a module for the server, the What Vite plugin compiles its JSX to string templates that every renderer on this page accepts, so the same components render on the server and in the browser. h() trees and components compiled for the server nest inside each other in both directions. Builds that do not use the Vite plugin set generate: "ssr" on the Babel plugin for their server bundle. The examples on this page use h(), which needs no build step at all; it is what the fullstack scaffold uses.
renderToString
The simplest way to render on the server. Pass a virtual node tree and get back a complete HTML string synchronously. Components are called as functions, event handlers are stripped, and all attributes are properly escaped:
import { h } from 'what-framework';
import { renderToString } from 'what-framework/server';
function Greeting({ name }) {
return h('div', { class: 'greeting' },
h('h1', {}, `Hello, ${name}!`),
h('p', {}, 'Welcome to the site.'),
);
}
const html = renderToString(
h(Greeting, { name: 'Alice' })
);
console.log(html);
// <div class="greeting"><h1>Hello, Alice!</h1><p>Welcome to the site.</p></div>
Use this in your server handler to return fully rendered HTML. It handles text nodes, arrays, nested components, void elements (like <img> and <br>), and properly escapes all attribute values and text content to prevent XSS.
To make that HTML interactive, the client calls hydrate(vnode, container) from what-framework with a tree that matches what the server rendered.
The client entry may go through what-compiler; the components it hydrates may not
hydrate() needs a tree it can still walk, so that it can match each vnode against the server's node and adopt it. what-compiler emits one for the JSX you hand it directly: hydrate(<App />) lowers to hydrate(_$componentVNode(App, ...)), which describes the component rather than running it, so the walk reaches the server's nodes and reuses them.
What that does not change is the component's own body. A component lowered by what-compiler for the client returns a cloned template, which is finished DOM, so hydrate() can only replace the server's markup with it and warn in development: the page is correct and interactive, but the server's nodes are not reused. For reuse today, write the components in a hydrated tree with h(), which is what the fullstack scaffold does, or with the automatic JSX runtime (jsxImportSource: "what-framework"), which compiles JSX down to h() calls.
renderToStream
Streaming sends the page shell to the browser as soon as it is rendered, instead of waiting for the slowest data on the page. Everything outside a <Suspense> that is still waiting goes out at once, with the fallback in place; each boundary follows when its data is ready, swapped in by a small inline script, with its data sent ahead of it for hydration. renderToStream returns a stream you consume once: pipe() it into a Node response, return its readable from a Fetch-style handler, or iterate its string chunks:
import { h } from 'what-framework';
import { renderToStream } from 'what-framework/server';
// In your server handler (Node.js example)
app.get('/', async (req, res) => {
res.setHeader('Content-Type', 'text/html');
const stream = renderToStream(
h(App, { url: req.url }),
{ nonce: res.locals.nonce } // set on every inline script
);
await stream.shellReady; // the shell rendered: status and headers are final
stream.pipe(res); // honours backpressure and ends the response
});
// Workers, Deno, Bun, Vercel: a Fetch-style handler
export default {
fetch(request) {
return new Response(renderToStream(h(App)).readable, { headers: { 'content-type': 'text/html' } });
},
};
Async components work too. Inside a <Suspense>, a component that returns a Promise makes that boundary stream later; outside any boundary, the shell waits for it. The browser can paint the page header and the fallbacks while the database query for the content is still running.
As with renderToString, useEffect bodies never run on the server, and onMount callbacks never run on either path. Keep browser-only work in onMount.
A stream is not a promise. For the whole page as one settled string (a cache, ISR, a crawler) use renderDocument or renderToStringAsync. With a strict CSP and no nonce, pass noScripts: true: boundaries still arrive as templates, and the client entry calls applyStreamedBoundaries() from what-framework before hydrating. Every error the render contains reaches onError(error, { phase }); production pages carry no error details.
definePage
Use definePage to declare how a page should be rendered. The call itself just returns your config with mode defaulting to 'static'; the static exporter and the deploy adapter are what read it. Four modes are recognized:
static(default) -- Pre-render at build time. The static exporter writes the route to disk, andgenerateStaticPagedrops your ownscriptsarray. Best for content that rarely changes.server-- Render on every request. The deploy adapter bypasses the ISR cache for this mode and answers withCache-Control: private, no-store. Use it for personalized or dynamic pages that depend on cookies, headers, or real-time data.client-- Not pre-rendered: the static exporter skips the route. It does not mean the server sends an empty shell, because both the request-time adapter andgenerateStaticPagestill render the component to real HTML.generateStaticPageadditionally appends<script type="module" src="/@what/client.js">, a URL no What runtime serves, so point the page at your own client entry instead.hybrid-- Pre-rendered at build time likestatic, with interactive islands layered on top. The best of both worlds for content-heavy pages with a few interactive widgets.
// src/pages/blog/[slug].js: static blog post, built once at deploy time
import { definePage } from 'what-framework/server';
export default definePage({
mode: 'static',
component: BlogPost,
title: 'My First Post',
meta: { description: 'An introduction to What Framework.' },
});
// src/pages/dashboard.js: server-rendered, fresh data on each request
import { definePage } from 'what-framework/server';
export default definePage({
mode: 'server',
component: Dashboard,
title: 'Dashboard',
});
// src/pages/products/[id].js: hybrid, static page plus a cart island
import { definePage } from 'what-framework/server';
export default definePage({
mode: 'hybrid',
component: ProductPage,
title: 'Widget Pro',
islands: ['AddToCart', 'ReviewSection'],
});
Server Components
server() tags a component as server-only. Be precise about what that buys you today: the whole implementation is Component._server = true, and nothing else in What reads that flag. There is no bundler integration, no compiler handling and no client/server split, so the component still ends up in your client bundle and its body still runs if the client renders it:
import { h } from 'what-framework';
import { server } from 'what-framework/server';
// Marks intent for your own tooling. It does not remove the
// component from the client bundle, so keep secrets out of it.
const UserProfile = server(function({ user }) {
return h('div', { class: 'profile' },
h('img', { src: user.avatar, alt: user.name }),
h('h2', {}, user.name),
h('p', {}, user.bio),
);
});
Do not put a database query, an env var or a secret inside a component and rely on server() to keep it off the client. The surfaces that genuinely only ever run on the server are a page module's export const loader, your own API routes, and the body of an action() reached through /__what_action. Fetch there, then pass plain data down as props to components like the one above.
Server Actions
Server actions let you define server-side functions that can be called directly from client code. Define an action on the server, and the client calls it via an automatic RPC mechanism over fetch:
import { action } from 'what-framework/server';
// Define a server action
const saveUser = action(async (data) => {
const user = await db.users.create(data);
return { success: true, id: user.id };
}, {
id: 'saveUser',
onSuccess: (result) => console.log('Saved:', result.id),
revalidate: ['/users'],
});
Give every action an explicit id unless you build with what-compiler, which supplies a deterministic one. Without either, action() generates a random id per process and warns; the client and server bundles then disagree about the name and every dispatch answers 404.
revalidate works on both sides. In the served endpoint it purges those paths from the ISR cache (with revalidateTags, the tags). On the client, the call is a transition: after the action answers, invalidatePath(path) refetches the queries and route data read on each path, and invalidates: [key] refetches query keys, inside that transition, so the screen goes from the old data to the new in one commit. The call resolves once those refetches have landed. See DATA.md.
useActionState
React 19's useActionState runs an action inside a transition and keeps its result. state and isPending are accessors; dispatches queue, each receiving the state the previous one returned, and the new state commits in the same flush as the data the action revalidated:
import { useActionState } from 'what-framework';
import { action } from 'what-framework/server';
const saveUser = action(async (data) => ({ id: 1, ...data }), { id: 'saveUser', revalidate: ['/users'] });
export function SaveButton() {
const [saved, save, isPending] = useActionState(async (previous, user) => {
try {
return { user: await saveUser(user) };
} catch (error) {
return { error: error.message };
}
}, null);
return (
<div>
<button onClick={() => save({ name: 'Alice' })} disabled={() => isPending()}>
{() => (isPending() ? 'Saving...' : 'Save User')}
</button>
{() => (saved()?.error ? <p class="error">{saved().error}</p> : null)}
{() => (saved()?.user ? <p class="success">Saved with ID: {saved().user.id}</p> : null)}
</div>
);
}
An error the action throws (instead of returning) reaches the nearest <ErrorBoundary>, as in React, and drops the dispatches queued behind it. The thunks make each dynamic part update on every path. Compiled, they are optional: what-compiler wraps any JSX expression that makes a zero-argument call in a reactive region. Without the compiler (h(), or the automatic JSX runtime) nothing is wrapped, so a bare read is evaluated once at creation.
<Form> and useFormStatus
<Form action> renders a real <form method="post">, so it submits with JavaScript disabled; on a mounted page it runs the action as a transition instead, and useFormStatus() inside it reads the submission:
import { useFormStatus } from 'what-framework';
import { action, Form } from 'what-framework/server';
const subscribe = action(async ({ email }) => ({ ok: !!email }), { id: 'subscribe' });
function Submit() {
const status = useFormStatus();
return <button disabled={() => status.pending()}>{() => (status.pending() ? 'Sending...' : 'Subscribe')}</button>;
}
export function Newsletter() {
return (
<Form action={subscribe} redirect="/thanks">
<input name="email" type="email" />
<Submit />
</Form>
);
}
A server action receives the fields as an object; a client function (the dispatch of useActionState) receives the FormData. The form is reset once the action has succeeded: its uncontrolled fields clear, and a controlled one keeps what its value or checked prop holds, as in React 19. Without JavaScript, the action endpoint answers 303 to redirect.
useOptimistic
Show the user an instant result while the server processes the real mutation. If the server call fails, the optimistic update is automatically rolled back:
import { signal, startTransition, useOptimistic } from 'what-framework';
function LikeButton({ postId, initialCount }) {
const likes = signal(initialCount);
// React 19's shape: [optimistic, addOptimistic]; optimistic() is an accessor
const [shown, addLike] = useOptimistic(likes, (count, delta) => count + delta);
const like = () => startTransition(async () => {
addLike(1); // shows +1 at once
const res = await fetch(`/api/posts/${postId}/like`, { method: 'POST' });
const { count } = await res.json();
// After an await, a write is a transition of its own
startTransition(() => likes(count));
});
return <button onClick={like}>Like ({() => shown()})</button>;
}
addLike(1) shows the optimistic count at once. The overlay lasts as long as the transition it was added in: when the transition commits, it drops in the same flush that shows the server's count, so the number never flickers, and when the action rejects, it drops alone (the count goes back) and the promise startTransition returns rejects. useOptimistic from what-framework/server is the same function. See ASYNC.md.
The thunk around shown() keeps the label following the optimistic state on every path. Compiled, a bare {shown()} works as well, since the compiler wraps a zero-argument call; with h() or the automatic JSX runtime it is inserted once and the count never moves.
CSRF Protection
Server actions include built-in CSRF protection. What provides utilities for token management and a fail-closed default that prevents silent security vulnerabilities:
import {
generateCsrfToken,
csrfMetaTag,
nodeActionMiddleware,
} from 'what-framework/server';
// Server: generate a token per session
app.use((req, res, next) => {
if (!req.session.csrfToken) {
req.session.csrfToken = generateCsrfToken();
}
next();
});
// Server: inject the token into your HTML
const html = `
<head>
${csrfMetaTag(req.session.csrfToken)}
</head>
`;
// Renders: <meta name="what-csrf-token" content="abc-123...">
// Server: mount the /__what_action endpoint
app.use(nodeActionMiddleware({
getCsrfToken: (req) => req.session.csrfToken,
}));
Mount the endpoint with nodeActionMiddleware rather than writing the route by hand. The client wrapper sends the action name in an X-What-Action header and posts only { args } as the body, while a plain no-JS form sends it as a hidden _action field, so a handwritten route that reads req.body.actionId answers 404 to every request. The middleware handles both shapes, parses the body by content type, caps it at 1 MB and then dispatches through handleActionRequest, which is the low-level dispatcher rather than a route handler. On edge runtimes (Deno, Bun, Cloudflare Workers) use fetchActionHandler({ getCsrfToken }) instead, which takes a Request and returns a Response.
The action endpoint first asks the browser where the request comes from. Every current browser sends Sec-Fetch-Site (or an Origin header) with a POST: a request it marks cross-site, or whose origin is not this host, is refused with 403, and one it marks same-origin passes without a token. That is how a form on a cached or streamed page posts, since its shared HTML can never carry a visitor's token. The token check below applies to requests that carry neither header, and to any request that sends a token anyway. createRequestHandler({ csrf: { trustedOrigins: ['https://app.example'] } }) lets other origins of the app post.
handleActionRequest uses fail-closed semantics: if no CSRF token reaches it, it returns a 500 error explaining the misconfiguration rather than silently accepting the request. Token comparison uses constant-time string matching to prevent timing attacks. The client reads the token from the <meta> tag automatically (falling back to the what-csrf cookie) and sends it with every action request.
Server Runtime Required
Server actions need a server runtime to handle the /__what_action endpoint. They work with Node.js, Deno, Bun, and edge runtimes such as Cloudflare Workers. For purely static sites without a server, use client-side fetch calls to your API instead of server actions.
Static Site Generation
Use generateStaticPage to pre-render pages at build time. It renders your page component through renderToString inside a server render scope, then wraps the output in a full HTML document with the configured title, meta tags, styles, and island scripts. Because the component gets a real component frame, a statically generated page can use useState, useSignal, useMemo, useRef and a root Context.Provider; as on every renderToString path, useEffect bodies are suppressed and onMount never runs. The data object is passed to the component as its props, minus a key field if you have one, which the vnode layer consumes:
import { generateStaticPage, definePage } from 'what-framework/server';
const page = definePage({
mode: 'hybrid',
component: BlogPost,
title: 'My Post',
meta: { description: 'A great article.' },
styles: ['/styles/blog.css'],
islands: ['CommentSection'],
});
const html = generateStaticPage(page, { slug: 'my-post' });
// Full HTML document with <!DOCTYPE html>, <head>, island hydration script
The island hydration script, a <script type="module"> that imports and calls hydrateIslands(), is emitted whenever the page declares a non-empty islands array, in any mode. What mode: 'static' changes is your own scripts array, which is dropped. The names inside islands are only used as a has-islands switch; they are never written into the document, so each island still needs its own Island marker in the component and its own island() registration on the client.
generateStaticPage drops <Head> tags
generateStaticPage opens a head sink for the render but never serializes it, so a <Head> declared inside the page contributes nothing to the document. The <head> it emits is built only from the title and meta you hand definePage. For per-page head tags, render with renderToStringWithHead and place the returned head string in your own document, or use renderDocument, which serializes the head into the document it returns and emits the hydration payload as well. Both were checked: each one carries the page's title, meta and link tags through. renderPage and renderToStringAsync return the same head string if you are already using one of them.
Both ways of writing a tag reach the head: <Head> collects its title, meta and link props, and its <title>, <meta> and <link> children, which share the props' dedup keys (a child beats a prop of the same <Head>). So h(Head, { meta: [{ name: 'description', content: '…' }] }) and <Head><meta name="description" content="…" /></Head> land in the same place. Any other child renders where the component sits, in the body.