Skip to content

Commit

Permalink
feat: Inject custom properties in SSR context. Closes #5
Browse files Browse the repository at this point in the history
  • Loading branch information
frandiox committed Feb 16, 2021
1 parent 4c95d23 commit add169f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
18 changes: 12 additions & 6 deletions core/entry-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,14 @@ export default function (App, { routes, base }, hook) {

await router.isReady()

const initialState = JSON.stringify(
router.currentRoute.value.meta.state || {}
)
// This can be injected with useSSRContext() in setup functions
const context = {
request,
...extra,
initialState: router.currentRoute.value.meta.state || {},
}

const ctx = {}
let html = await renderToString(app, ctx)
let html = await renderToString(app, context)

const [helmet = ''] = html.match(/<html[^>]*?>(.|\s)*?<\/html>/im) || []
let [, head = ''] = helmet.match(/<head[^>]*?>((.|\s)*?)<\/head>/im) || []
Expand All @@ -59,11 +61,15 @@ export default function (App, { routes, base }, hook) {
html = html.replace(helmet, '<!---->')
}

const dependencies = manifest ? findDependencies(ctx.modules, manifest) : []
const dependencies = manifest
? findDependencies(context.modules, manifest)
: []
if (preload && dependencies.length > 0) {
head += renderPreloadLinks(dependencies)
}

const initialState = JSON.stringify(context.initialState || {})

return {
// This string is replaced at build time
// and injects all the previous variables.
Expand Down
14 changes: 12 additions & 2 deletions example/src/pages/Homepage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
</template>

<script>
export default {
import { defineComponent } from 'vue'
export default defineComponent({
name: 'Homepage',
props: {
server: {
Expand All @@ -27,11 +29,19 @@ export default {
},
},
setup() {
// This will be removed from the client build
if (import.meta.env.SSR) {
// Vite/plugin-vue is injecting this function in the setup scope
const { initialState } = useSSRContext()
// Initial state is mutable and will be hydrated in the client
initialState.perkele = true
}
return {
json: JSON.stringify({ something: true }),
}
},
}
})
</script>
<style scoped>
Expand Down

0 comments on commit add169f

Please sign in to comment.