⚠
vite-plugin-ssr has been renamed Vike, see migration guide.

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
    }
  }
}

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
}

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.