// /pages/movie/+onBeforePrerenderStart.js// Environment: Node.jsexport { onBeforePrerenderStart }async function onBeforePrerenderStart() { const movies = await Movie.findAll() const moviePages = ( movies .map(movie => { const url = '/movie/' + movie.id const pageContext = { data: { movie } } return { url, // Because we already provide the `pageContext`, Vike will *not* call // the `data()` (nor the `onBeforeRender()`) hook for `url`. pageContext } /* We could also only return `url` and not provide `pageContext`. In that case * Vike would call the `data()` (and `onBeforeRender()`) hook. But that would be wasteful * since we already have all the data of all movies from our `await Movie.findAll()` call. * Instead, we provide `pageContext` to make the pre-rendering build step faster. */ // return { url } }) ) // We can also return URLs that don't match the page's route. // That way we can provide the `pageContext` of other pages. // Here we provide the `pageContext` of the `/movies` page since // we already have the data. const movieListPage = { url: '/movies', // Note how this URL '/movies' doesn't match the page's route /movie/@movieId pageContext: { data: { // We filter out the data we don't need in order to minimize what is sent // to the browser. We explain this practice at https://vike.dev/data-fetching movieList: movies.map(({id, title}) => ({id, title}) } } } return [movieListPage, ...moviePages]}
Essentially, the onBeforePrerenderStart() hook allows us to prefetch data for multiple pages at once.
Providing pageContext in onBeforePrerenderStart() hooks should only be used for making the pre-rendering build step faster and
we recommend against using onBeforePrerenderStart() hooks for other purposes.
For example, we should avoid providing additional pageContext in onBeforePrerenderStart() hooks that wouldn't otherwise exist.
Instead, we should make sure that our data() and onBeforeRender() hooks provide all the pageContext we need.
The reason being that onBeforePrerenderStart() hooks are never called in development and we should keep our app consistent between development and production.
export { onBeforePrerenderStart }import type { OnBeforePrerenderStartAsync } from 'vike/types'const onBeforePrerenderStart: OnBeforePrerenderStartAsync = async (): ReturnType<OnBeforePrerenderStartAsync> => { // ...}
Don't omit ReturnType<OnBeforePrerenderStartAsync> (don't write const onBeforePrerenderStart: OnBeforePrerenderStartAsync = async (pageContext) => {), otherwise TypeScript won't strictly check the return type for unknown extra properties: see this TypeScript playground and issue.