⚠️
The vite-plugin-ssr project has been renamed Vike.
  • If you are already using vite-plugin-ssr then migrate to Vike.
  • For new projects, don't use vite-plugin-ssr but use Vike instead.

onBeforeRender() hook (.page.js)

In general, we recommend defining onBeforeRender() hooks in .page.server.js instead of .page.js. (We elaborate below.)

Defining onBeforeRender() in .page.js only works when using Client Routing.

Usually, we define onBeforeRender() in .page.server.js but, if we use Client Routing, then we also have the option to define onBeforeRender() in .page.js instead.

When defined in .page.server.js the onBeforeRender() hook is only loaded & executed in Node.js, whereas if we define it in .page.js then onBeforeRender() is also loaded & executed in the browser: for the first page the user visits onBeforeRender() is called in Node.js while for any subsequent page navigation onBeforeRender() is called in the browser.

Examples:

Recommendation

In general, we recommend defining onBeforeRender() hooks in .page.server.js since it's easier to write code that only runs in Node.js.

That said, if we want to minimize requests made to our Node.js server, then we may want to define our onBeforeRender() hooks in .page.js. But then we need to ensure that our onBeforeRender() hook is isomorphic: it needs to be able to run in both Node.js and the browser.

Server Routing

If we use Server Routing we shouldn't define onBeforeRender() in .page.js (the browser loads onBeforeRender() but never calls it). We should always define onBeforeRender() in .page.server.js instead.