⚠️
The vite-plugin-ssr project has been renamed Vike.
  • If you are already using vite-plugin-ssr then migrate to Vike.
  • For new projects, don't use vite-plugin-ssr but use Vike instead.

Access pageContext anywhere

By default pageContext is available:

  • only on the server-side, and
  • only at the root component Page.

But we can make pageContext available anywhere.

Browser-side

To make pageContext available in the browser, we use passToClient.

React

We can use React Context to make pageContext accessible from any React component.

Example:

Vue 3 - Composition API

We can use app.provide() with inject() to make pageContext accessible from any Vue component.

// app.js

const app = createSSRApp(/*...*/)
app.provide('pageContext', pageContext)
<!-- someComponent.vue -->

<template>
  <!-- We can access `pageContext` here -->
  {{ pageContext.someProp }}
</template>

<script setup>
import { inject } from 'vue'
const pageContext = inject('pageContext')
</script>

We can also implement a usePageContext() hook:

// usePageContext.js

import { inject } from 'vue'

export { usePageContext }
export { setPageContext }

const key = Symbol()

function usePageContext() {
  const pageContext = inject(key)
  return pageContext
}
function setPageContext(app, pageContext) {
  app.provide(key, pageContext)
}
const app = createSSRApp(/*...*/)
setPageContext(app, pageContext)
<script setup>
import { usePageContext } from './path/to/usePageContext'
const pageContext = usePageContext()
</script>

Example:

If we use Client Routing, we need to make pageContext reactive:

Vue 3 - globalProperties

Alternatively, we can make pageContext available to all Vue components by using app.config.globalProperties.

// app.js

const app = createSSRApp(/*...*/)
app.config.globalProperties.$pageContext = pageContext
<!-- someComponent.vue -->

<template>
  <!-- We can access `pageContext` here -->
  {{ $pageContext.someProp }}
</template>

<script setup>
import { getCurrentInstance } from 'vue'
// We can access `pageContext` here
const pageContext = getCurrentInstance().appContext.config.globalProperties.$pageContext
</script>

Example:

If we use Client Routing, we make $pageContext reactive:

Vue 2

For Vue 2 we can use Vue.prototype.