Skip to main content
You’re reading the documentation for Vue InstantSearch v4. Read the migration guide to learn how to upgrade from v3 to v4. You can still find the v3 documentation for this page.
Server-side rendering (SSR) describes a technique for rendering websites. When you request an SSR page, the HTML is rendered on the server and then sent to your client. The main steps to implement server-side rendering with Algolia are: On the server:
  1. Request search results from Algolia
  2. Render the Vue app with the results of the request
  3. Store the search results in the page
  4. Return the HTML page as a string
On the client:
  1. Read the search results from the page
  2. Render (or hydrate) the Vue app with the search results
You can build server-side rendered apps with Vue.js in different ways—for example, using the Vue CLI or Nuxt.js. For code examples, see these GitHub repositories:

With Vue CLI

  1. Create a Vue app with Vue CLI and add the SSR plugin:
    vue create algolia-ssr-example
    cd algolia-ssr-example
    vue add router
    vue add @akryum/ssr
    
  2. Start the development server by running: npm run ssr:serve.
  3. Install Vue InstantSearch
  4. Add Vue InstantSearch to your app in the src/main.js file:
    import {
      AisInstantSearchSsr,
      createServerRootMixin,
    } from "vue-instantsearch/vue3/es";
    
    Vue.use(VueInstantSearch);
    
  5. Create a new page src/views/Search.vue and build a search interface:
    Vue
    <template>
    <ais-instant-search :search-client="searchClient" index-name="instant_search">
        <ais-search-box />
        <ais-stats />
        <ais-refinement-list attribute="brand" />
        <ais-hits>
        <template v-slot:item="{ item }">
            <p>
            <ais-highlight attribute="name" :hit="item" />
            </p>
            <p>
            <ais-highlight attribute="brand" :hit="item" />
            </p>
        </template>
        </ais-hits>
        <ais-pagination />
    </ais-instant-search>
    </template>
    
    <script>
    import { liteClient as algoliasearch } from 'algoliasearch/lite';
    const searchClient = algoliasearch(
    'latency',
    '6be0576ff61c053d5f9a3225e2a90f76'
    );
    
    export default {
    data() {
        return {
        searchClient,
        };
    },
    };
    </script>
    
  6. Add a route to this page in src/router.js:
    JavaScript
    import Vue from "vue";
    import Router from "vue-router";
    import Home from "./views/Home.vue";
    import Search from "./views/Search.vue";
    
    Vue.use(Router);
    
    export function createRouter() {
      return new Router({
        mode: "history",
        base: process.env.BASE_URL,
        routes: [
          /* ... */
          {
            path: "/search",
            name: "search",
            component: Search,
          },
        ],
      });
    }
    
  7. Update the header in src/App.vue:
    Vue
    <template>
    <div id="app">
    <div id="nav">
        <router-link to="/">Home</router-link> |
        <router-link to="/about">About</router-link> |
        <router-link to="/search">Search</router-link>
    </div>
    <router-view />
    </div>
    </template>
    
  8. For styling, add instantsearch.css to public/index.html:
    HTML
    <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/satellite-min.css"
        integrity="sha256-woeV7a4SRDsjDc395qjBJ4+ZhDdFn8AqswN1rlTO64E="
        crossorigin="anonymous"
    />
    
  9. Vue InstantSearch uses ES modules, but the app runs on the server, with Node.js. That’s why you need to add these modules to the vue.config.js configuration file:
    JavaScript
    module.exports = {
      pluginOptions: {
        ssr: {
          nodeExternalsWhitelist: [
            /\.css$/,
            /\?vue&type=style/,
            /vue-instantsearch/,
            /instantsearch.js/,
          ],
        },
      },
    };
    
    At this point, Vue.js renders the app on the server. But when you go to /search in your browser, you won’t see the search results on the page. That’s because, by default, Vue InstantSearch starts searching and showing results after the page is rendered for the first time.
  10. To perform searches on the backend as well, you need to create a backend instance in src/main.js:
    import VueInstantSearch, {
      createServerRootMixin,
    } from "vue-instantsearch/vue3/es";
    import { liteClient as algoliasearch } from "algoliasearch/lite";
    
    const searchClient = algoliasearch(
      "latency",
      "6be0576ff61c053d5f9a3225e2a90f76",
    );
    
    export async function createApp({
      renderToString,
      beforeApp = () => {},
      afterApp = () => {},
    } = {}) {
      const router = createRouter();
    
      //Pprovide access to all components
      Vue.use(VueInstantSearch);
    
      await beforeApp({
        router,
      });
    
      const app = new Vue({
        // Provide access to the instance
        mixins: [
          createServerRootMixin({
            searchClient,
            indexName: "instant_search",
          }),
        ],
        serverPrefetch() {
          return this.instantsearch.findResultsState({
            component: this,
            renderToString,
          });
        },
        beforeMount() {
          if (typeof window === "object" && window.__ALGOLIA_STATE__) {
            this.instantsearch.hydrate(window.__ALGOLIA_STATE__);
            delete window.__ALGOLIA_STATE__;
          }
        },
        router,
        render: (h) => h(App),
      });
    
      const result = {
        app,
        router,
      };
    
      await afterApp(result);
    
      return result;
    }
    
    The Vue app can now inject the backend instance of Vue InstantSearch.
  11. In the main file, replace ais-instant-search with ais-instant-search-ssr. You can also remove its props since they’re now passed to the createServerRootMixin function.
    Vue
    <template>
      <ais-instant-search-ssr>
        <!-- ... -->
      </ais-instant-search-ssr>
    </template>
    
  12. To save the results on the backend, add the InstantSearch state to the context using the getState function:
    JavaScript
    import _renderToString from "vue-server-renderer/basic";
    import { createApp } from "./main";
    
    function renderToString(app) {
      return new Promise((resolve, reject) => {
        _renderToString(app, (err, res) => {
          if (err) reject(err);
          resolve(res);
        });
      });
    }
    
    export default (context) => {
      return new Promise(async (resolve, reject) => {
        // Read the provided instance
        const { app, router, instantsearch } = await createApp({ renderToString });
    
        router.push(context.url);
    
        router.onReady(() => {
          // Save the results once rendered fully.
          context.rendered = () => {
            context.algoliaState = app.instantsearch.getState();
          };
    
          const matchedComponents = router.getMatchedComponents();
    
          // Find the root component that handles the rendering
          Promise.all(
            matchedComponents.map((Component) => {
              if (Component.asyncData) {
                return Component.asyncData({
                  route: router.currentRoute,
                });
              }
            }),
          ).then(() => resolve(app));
        }, reject);
      });
    };
    
  13. Rehydrate the app with the initial request once you start searching. For this, you need to save the data on the page. Vue CLI provides a way to read the value on the context and save it in public/index.html:
    HTML
    <!DOCTYPE html>
    <html>
       <body>
       <!--vue-ssr-outlet-->
       {{{ renderState() }}}
       {{{ renderState({ contextKey: 'algoliaState', windowKey: '__ALGOLIA_STATE__' }) }}}
       {{{ renderScripts() }}}
       </body>
    </html>
    

With Nuxt 2

The following section describes how to set up server-side rendering with Vue InstantSearch and Nuxt 2. Check the community for solutions for Nuxt 3. First, create a Nuxt app and add vue-instantsearch:
npx create-nuxt-app algolia-nuxt-example
cd algolia-nuxt-example
npm install vue-instantsearch algoliasearch
Vue InstantSearch uses ES modules, but the app runs on the server, with Node.js. That’s why you need to add these modules to the nuxt.config.js configuration file:
JavaScript
module.exports = {
  build: {
    transpile: ["vue-instantsearch", "instantsearch.js/es"],
  },
};
Create a new page pages/search.vue and build a Vue InstantSearch interface:
Vue
<template>
  <ais-instant-search :search-client="searchClient" index-name="instant_search">
    <ais-search-box />
    <ais-stats />
    <ais-refinement-list attribute="brand" />
    <ais-hits>
      <template v-slot:item="{ item }">
        <p>
          <ais-highlight attribute="name" :hit="item" />
        </p>
        <p>
          <ais-highlight attribute="brand" :hit="item" />
        </p>
      </template>
    </ais-hits>
    <ais-pagination />
  </ais-instant-search>
</template>
Add the component declarations and the style sheet:
import {
  AisInstantSearch,
  AisRefinementList,
  AisHits,
  AisHighlight,
  AisSearchBox,
  AisStats,
  AisPagination,
  createServerRootMixin,
} from "vue-instantsearch/vue3/es";
import { liteClient as algoliasearch } from "algoliasearch/lite";

const searchClient = algoliasearch(
  "latency",
  "6be0576ff61c053d5f9a3225e2a90f76",
);

export default {
  components: {
    AisInstantSearch,
    AisRefinementList,
    AisHits,
    AisHighlight,
    AisSearchBox,
    AisStats,
    AisPagination,
  },
  data() {
    return {
      searchClient,
    };
  },
  head() {
    return {
      link: [
        {
          rel: "stylesheet",
          href: "https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/satellite-min.css",
        },
      ],
    };
  },
};
  1. Add createServerRootMixin to create a reusable search instance.
  2. Add findResultsState in serverPrefetch to perform a search query in the backend.
  3. Call the hydrate method in beforeMount.
  4. Replace ais-instant-search with ais-instant-search-ssr
  5. Add the createRootMixin to provide the instance to the component.
    <template>
    <ais-instant-search-ssr>
        <ais-search-box />
        <ais-stats />
        <ais-refinement-list attribute="brand" />
        <ais-hits>
        <template v-slot:item="{ item }">
            <p>
            <ais-highlight attribute="name" :hit="item" />
            </p>
            <p>
            <ais-highlight attribute="brand" :hit="item" />
            </p>
        </template>
        </ais-hits>
        <ais-pagination />
    </ais-instant-search-ssr>
    </template>
    
    <script>
    import {
    AisInstantSearchSsr,
    AisRefinementList,
    AisHits,
    AisHighlight,
    AisSearchBox,
    AisStats,
    AisPagination,
    createServerRootMixin,
    } from 'vue-instantsearch/vue3/es';
    import { liteClient as algoliasearch } from 'algoliasearch/lite';
    import _renderToString from 'vue-server-renderer/basic';
    
    function renderToString(app) {
    return new Promise((resolve, reject) => {
        _renderToString(app, (err, res) => {
        if (err) reject(err);
        resolve(res);
        });
    });
    }
    
    const searchClient = algoliasearch(
    'latency',
    '6be0576ff61c053d5f9a3225e2a90f76'
    );
    
    export default {
    mixins: [
        createServerRootMixin({
        searchClient,
        indexName: 'instant_search',
        }),
    ],
    serverPrefetch() {
        return this.instantsearch
        .findResultsState({
            component: this,
            renderToString,
        }).then(algoliaState => {
            this.$ssrContext.nuxt.algoliaState = algoliaState;
        });
    },
    beforeMount() {
        const results =
        (this.$nuxt.context && this.$nuxt.context.nuxtState.algoliaState) ||
        window.__NUXT__.algoliaState;
    
        this.instantsearch.hydrate(results);
    
        // Remove the SSR state so it can't be applied again by mistake
        delete this.$nuxt.context.nuxtState.algoliaState;
        delete window.__NUXT__.algoliaState;
    },
    components: {
        AisInstantSearchSsr,
        AisRefinementList,
        AisHits,
        AisHighlight,
        AisSearchBox,
        AisStats,
        AisPagination,
    },
    head() {
        return {
        link: [
            {
            rel: 'stylesheet',
            href: 'https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/satellite-min.css',
            },
        ],
        };
    },
    };
    </script>
    
I