onAfterRenderHtml() hook

Environment: server.

Implemented by: vike-react/vike-vue.

You need vike-react/vike-vue to be able to use onAfterRenderHtml(). If you don't use vike-react/vike-vue then see Without vike-{react,vue,solid}.

Hook called right after the the +Page component is rendered to HTML.

Lifecycle

It's called upon rendering the first page the user visits. It isn't called upon page navigation (since pages aren't rendered to HTML upon page navigation).

It's called regardless of whether SSR is disabled. (The first page the user visits is always rendered to HTML: when SSR is disabled it's just an HTML shell that doesn't contain the content of the page.)

For pre-rendered pages it's called at build-time. (Since the HTML of pre-rendered pages are generated at build-time.)

Conditional

You can apply onAfterRenderHtml() only upon certain conditions, for example you can apply it only if SSR is enabled.

pageContext.pageHtml{String,Stream}

To access the page's HTML string/stream:

// +onAfterRenderHtml.js
 
export function onAfterRenderHtml(pageContext) {
  // The +Page.js component rendered to an HTML string
  pageContext.pageHtmlString
  // The +Page.js component rendered to an HTML stream
  pageContext.pageHtmlStream
}

Use cases

The onAfterRenderHtml() and onBeforeRenderHtml() hooks are typically used for integrating tools.

For example, onAfterRenderHtml() is often used for dehydrating state management libraries, and onBeforeRenderHtml() can be used for collecting the page's CSS defined by a CSS-in-JS library (#141 - CSS-in-JS with SSR).

Without vike-{react,vue,solid}

If you don't use a UI framework Vike extension vike-react/vike-vue/vike-solid, then you don't need onAfterRenderHtml() nor onBeforeRenderHtml() since you already have full control over HTML rendering at your onRenderHtml() hook.

See also