Skip to content

docs: using vue-instantsearch with ssr #143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 55 additions & 1 deletion docs/content/2.advanced/1.vue-instantsearch.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Next, let's create `indexName` variable, call `useAlgolia` composable in page.vu
<script lang="ts" setup>
const indexName = 'test_index'
const algolia = useAlgoliaRef()
import { AisInstantSearch, AisSearchBox, AisHits } from 'vue-instantsearch/vue3/es/index.js'
import { AisInstantSearch, AisSearchBox, AisHits } from 'vue-instantsearch/vue3/es'
</script>
```

Expand All @@ -48,3 +48,57 @@ Finally, let's use it in our page.vue template section with vue-instantsearch co
</div>
</template>
```

## Using vue-instantsearch with SSR

Server-side rendering requires a few extra steps. First, extract `instantsearch` instance from the mixin and provide it to all `vue-instantsearch` components:

```ts
import { createServerRootMixin } from 'vue-instantsearch/vue3/es'
import { renderToString } from 'vue/server-renderer'

const serverRootMixin = ref(
createServerRootMixin({
searchClient: algolia,
indexName,
}),
)

const { instantsearch } = serverRootMixin.value.data()

provide('$_ais_ssrInstantSearchInstance', instantsearch)
```

Then load the results using `useAsyncData` and hydrate them on the client:

```ts
onBeforeMount(() => {
// Use data loaded on the server
if (algoliaState.value) {
instantsearch.hydrate(algoliaState.value)
}
})

const { data: algoliaState } = await useAsyncData('algolia-state', async () => {
return instantsearch.findResultsState({
// IMPORTANT: a component with access to `this.instantsearch` to be used by the createServerRootMixin code
component: {
$options: {
components: { AisInstantSearchSsr, AisRefinementList, AisSortBy },
data() {
return { instantsearch }
},
provide: { $_ais_ssrInstantSearchInstance: instantsearch },
render() {
return h(AisInstantSearchSsr, null, () => [
// Include any vue-instantsearch components that you use including each refinement attribute
h(AisRefinementList, { attribute: 'languages' }),
h(AisSortBy, { items: [{ value: indexName, label: '' }] }),
])
},
},
},
renderToString,
})
})
```