pageContext.json

Upon page navigation, Vike makes a pageContext.json HTTP request to your server, in order to pass data fetched on the server-side (e.g. with data()) to the client-side.

HTTP GET /star-wars/index.pageContext.json

Example

// /pages/star-wars/+data.server.js
 
// This data() hook is always called on the server-side. But, upon page navigation, the data
// needs to be available on the client-side thus Vike makes a /star-wars/index.pageContext.json
// request in order to pass the data from the server to the client.
export async function data() {
  const response = await fetch('https://star-wars.brillout.com/api/films.json')
  const movies = await response.json()
  return { movies }
}

The request /star-wars/index.pageContext.json returns the data fetched by the data() hook.

$ curl /star-wars/index.pageContext.json
{
  "data": {
    "movies": [
      {
        "title": "A New Hope",
        "release_date": "1977-05-25"
      },
      {
        "title": "The Empire Strikes Back",
        "release_date": "1980-05-17"
      },
      {
        "title": "Return of the Jedi",
        "release_date": "1983-05-25"
      }
    ]
  }
}

Avoid pageContext.json requests

If you want to minimize requests made to your server, then you may want Vike to stop making pageContext.json requests.

Most commonly, if the data you fetch comes from another server, then you typically don't want to make an unnecessary detour over your JavaScript/SSR server.

Vike makes a pageContext.json request for a page if and only if one of the two following conditions is true:

  • The page has a server-only data() or onBeforeRender() hook.

    See:

  • The pageContextInit at renderPage() contains a property that is included in passToClient.
    // Vike server middleware
    async (req, res, next) => {
      const pageContextInit = {
        urlOriginal: req.originalUrl,
        // If passToClient contains 'user' then Vike makes a pageContext.json request
        // upon page navigation in order the retrieve the pageContextInit.user value.
        user: req.user
      }
      const pageContext = await renderPage(pageContextInit)
      return pageContext.httpResponse
    }

If both conditions are false, then Vike won't make a pageContext.json request upon page navigation.