Server-rendering Stencil components in a SolidStart app.
The server's HTML, with JavaScript off.
pnpm install && pnpm build # at the repo root, once
pnpm dev # in this folder: http://localhost:3005Render the page as one string instead of streaming it, with mode: 'async'
(src/entry-server.tsx). Then a middleware passes it through
renderToString() (src/middleware.ts):
import { createMiddleware } from '@solidjs/start/middleware';
import { renderToString } from '@ssr-examples/components/ssr';
export default createMiddleware([
async (event, next) => {
const body = await next();
if (typeof body !== 'string' || !event.res.headers.get('content-type')?.includes('text/html')) {
return body;
}
const { html, diagnostics } = await renderToString(body, { reuseWindow: true });
for (const d of diagnostics) console.warn('[stencil]', d.messageText);
return html ?? body;
},
]);Register it with solidStart({ middleware: './src/middleware.ts' }) in
vite.config.ts.
Mount once defineCustomElements() resolves (src/entry-client.tsx):
import { mount, StartClient } from '@solidjs/start/client';
import { defineCustomElements } from '@ssr-examples/components/loader';
defineCustomElements().then(() => mount(() => <StartClient />, document.getElementById('app')!));Don't define them later, such as in onMount: Solid would fail with a hydration mismatch and
throw the server-rendered page away.
Import the JSX types the library generates for Solid
(src/custom-elements.d.ts), then use them like any element (src/routes/index.tsx):
import { ssrProp } from '@ssr-examples/components/ssr-prop';
<demo-counter start={5} step={2} on:countChanged={(e) => setLastCount(e.detail)} />
<demo-stats stats={ssrProp(stats())} />- Objects and arrays: wrap them in
ssrProp(), or Solid leaves them out of the server HTML. In the browser it returns the value as it is. See Passing objects and arrays. - Events: write
on:countChanged.onCountChangedlistens forcountchanged, which never fires. - No
prop:: Solid's server renderer dropsprop:bindings, so the server HTML gets no value. A plain binding is already set as a property in the browser.
