The onBeforeRender() hook is for expert Vike users. If you're new to Vike, we recommend using the
data() hook instead, and/or Vike extensions for
automatically integrating data fetching tools (RPC with Telefunc/tRPC, REST with Tanstack Query, GraphQL with Apollo/Relay, etc).
The most notable use case for the onBeforeRender() hook is deep integration with data fetching tools.
For simple data fetching needs, use the data() hook instead. As a strategy to decide which one to use, always first try to use data() and only use onBeforeRender() as a fallback if data() doesn't work out.
Another common use case is to use onBeforeRender() as a global initializing hook. (As a temporary workaround until #962 - New hook onBoot() is implemented.)
onBeforeRender() VS data()
The central difference between the two hooks is that the value returned by data() always sets the value of pageContext.data, whereas onBeforeRender() can set multiple pageContext values.
Another difference is that the entire pageContext.data value is always sent to the client-side, whereas with onBeforeRender() you can (and have to) decide which values are sent to the client-side by using passToClient.
In a nutshell: while onBeforeRender() requires more manual work, it also gives you more control.
There can be only one onBeforeRender() hook per page. For example, if you define a global onBeforeRender() hook at /pages/+onBeforeRender.js as well as a page-specific one at /pages/star-wars/+onBeforeRender.js then the page-specific one overrides the global one. See API > Config > Inheritance.
If you want multiple onBeforeRender() hooks, then consider:
Creating custom hooks instead: you can then use one global onBeforeRender() hook that orchestrates many custom hooks.
Using data() hooks: you can then use one global onBeforeRender() while using page-specific data() hooks.
You can also suppress globally defined onBeforeRender() hooks on a per-page basis:
Advanced example
The following is an advanced example of using onBeforeRender() with meta in order to integrate data fetching tools. In particular, this approach can be used for advanced integration with GraphQL tools.
If you use a custom renderer instead of vike-react/vike-vue/vike-solid, then you can modify your onRenderHtml()/onRenderClient() hooks instead of doing the following.
Don't omit ReturnType<OnBeforeRenderAsync> (don't write const onBeforeRender: OnBeforeRenderAsync = async (pageContext) => {), otherwise TypeScript won't strictly check the return type for unknown extra properties: see this TypeScript playground and issue.