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 (and shouldn't) 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>
    <html>
      <head>
        <title>My SSR App</title>
      </head>
      <body>
        <div id="page-root">${dangerouslySkipEscape(pageHtml)}</div>
      </body>
    </html>`
 
  return {
    documentHtml,
    pageContext: {
      // We can define pageContext values here
    }
  }
}

Where pageContext.Page is the +Page value of the page that is being rendered.

TypeScript

// /**/+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> otherwise TypeScript won't strictly check the return type.

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

See also