In version 6.x.x, the SSR API was updated to use the server module only on the server. A key improvement is searchClient hydration: the results retrieved on the server are reused on the client, avoiding redundant initial requests.
To implement SSR:
- On the Server: Use
findResultsState from react-instantsearch-dom/server. You must now pass an options object containing indexName and searchClient to findResultsState. - On the Client: Pass the
indexName and searchClient as props to your application during hydration. - In your App component: The
InstantSearch component should receive indexName, searchClient, and resultsState as props.
// server.js
import { findResultsState } from "react-instantsearch-dom/server";
const indexName = "instant_search";
const searchClient = algoliasearch("latency", "API_KEY");
server.get("/", async (req, res) => {
const initialState = {
resultsState: await findResultsState(App, {
indexName,
searchClient
})
};
const plainHTML = renderToString(<App {...initialState} />);
// ...
});
// browser.js
hydrate(
<App
{...window.__APP_INITIAL_STATE__}
indexName={indexName}
searchClient={searchClient}
/>,
document.getElementById("root")
);
// App.js
import { InstantSearch, SearchBox } from "react-instantsearch-dom";
const App = ({ indexName, searchClient, resultsState }) => (
<InstantSearch
indexName={indexName}
searchClient={searchClient}
resultsState={resultsState}
>
<SearchBox />
</InstantSearch>
);