🍡 mochi

SSR framework for Svelte 5 + Bun with islands-based selective hydration

Transforming HTML with transformPageChunk

transformPageChunk is a resolve option that lets middleware transform the final HTML before it’s sent to the client. It only runs on text/html responses.

import type { Handle } from 'mochi-framework/hooks';

const greeting: Handle = async ({ event, resolve }) => {
  return resolve(event, {
    transformPageChunk({ html }) {
      return html.replace('{{app.greeting}}', 'Welcome to Mochi!');
    },
  });
};

Add a {{app.greeting}} placeholder anywhere in your HTML shell, and the middleware will replace it on every page response:

<body>
  <header>{{app.greeting}}</header>
  {{mochi.body}}
</body>

The callback receives { html, done } and can return a string, undefined, or a Promise — so async transforms work too:

const inject: Handle = async ({ event, resolve }) => {
  return resolve(event, {
    async transformPageChunk({ html }) {
      const banner = await fetchBannerMessage();
      return html.replace('{{app.banner}}', banner);
    },
  });
};

When multiple handlers in a sequence() use transformPageChunk, they run in reverse order — inner handlers transform first, then outer handlers receive the result.