onRenderHtml() hook

Environment: server.

The onRenderHtml() hook defines how pages are rendered to HTML.

The onRenderHtml() and onRenderClient() hooks are essentially the glue code between Vike and the UI framework (React/Vue/Solid/...).

If you use a UI framework Vike extension vike-react/vike-vue/vike-solid, then you don't need to define onRenderHtml() as it's already defined by vike-react/vike-vue/vike-solid.

// +onRenderHtml.js
// Environment: server
import { escapeInject, dangerouslySkipEscape } from 'vike/server'
import { renderToHtml, createElement } from 'some-ui-framework'
export { onRenderHtml }
async function onRenderHtml(pageContext){
  const { Page, data } = pageContext
  const pageHtml = await renderToHtml(createElement(Page, data))
  const documentHtml = escapeInject`<!DOCTYPE html>
        <title>My SSR App</title>
        <div id="page-root">${dangerouslySkipEscape(pageHtml)}</div>
  return {
    pageContext: {
      // We can define pageContext values here

Where pageContext.Page is the Page value of the page that is being rendered, see API > <Page>.


// /**/+onRenderHtml.ts (usually /renderer/+onRenderHtml.ts)
// Environment: server
export { onRenderHtml }
import type { OnRenderHtmlAsync } from 'vike/types'
import { escapeInject, dangerouslySkipEscape } from 'vike/server'
import { renderToHtml, createElement } from 'some-ui-framework'
const onRenderHtml: OnRenderHtmlAsync = async (pageContext): ReturnType<OnRenderHtmlAsync> => {
  // ...

Don't omit ReturnType<OnRenderHtmlAsync> (don't write const onRenderHtml: OnRenderHtmlAsync = async (pageContext) => {), otherwise TypeScript won't strictly check the return type for unknown extra properties: see this TypeScript playground and issue.

See API > pageContext > Typescript for more information on how to extend pageContext with your own extra properties.

See also