onBeforeRender() hook (.page.server.js)

The onBeforeRender() hook is usually used together with passToClient to fetch data, see Guides > Data Fetching.

Since .page.server.js is only loaded in Node.js, ORM/SQL database queries can be used.

// /pages/movies.page.server.js

// Note how we use `node-fetch`; this file is only run in Node.js thus we don't need
// to use an isomorphic (aka universal) implementation such as `cross-fetch`.
import fetch from 'node-fetch'

export { onBeforeRender }

async function onBeforeRender(pageContext){
  const response = await fetch("https://api.imdb.com/api/movies/")
  const { movies } = await response.json()
  /* Or with an ORM:
  const movies = Movie.findAll() */
  /* Or with SQL:
  const movies = sql`SELECT * FROM movies;` */
  return {
    pageContext: {
      pageProps: {
        movies
      }
    }
  }
}

Examples:

You can also provide initial pageContext values at your server middleware with renderPage(pageContextInit). This is where you usually pass information about the authenticated user (see Guides > Authentication).

If you use the V1 design, you can suppress globally defined onBeforeRender() hooks:

// /pages/+onBeforeRender.js

// Some global onBeforeRender() hook
export default () => {
  // ...
}
// /pages/some-page/+config.h.js

export default {
  // Suppress the global onBeforeRender() hook
  onBeforeRender: null
}

TypeScript

export { onBeforeRender }

import type { OnBeforeRenderAsync } from 'vike/types'

const onBeforeRender: OnBeforeRenderAsync = async (
  pageContext
): ReturnType<OnBeforeRenderAsync> => {
  const response = await fetch("https://api.imdb.com/api/movies/")
  const { movies } = await response.json()
  return {
    pageContext: {
      pageProps: {
        movies
      }
    }
  }
}
⚠
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.

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

Client Routing

If you use clientRouting, you also have the option to define onBeforeRender() in .page.js instead of .page.server.js; the hook is then called not only in Node.js but also in the browser.