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: {
      movies
    }
  }
}

We can also provide initial pageContext values at our server middlware (see createPageRenderer()) which is where we usually pass information about the authenticated user (see Integration > Authentication).

Examples:

Client Routing

If we use useClientRouter(), we 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.

Multiple onBeforeRender()

For a given page, we can define multiple onBeforeRender() hooks.