Skip to main content
This is the React InstantSearch v7 documentation. If you’re upgrading from v6, see the upgrade guide. If you were using React InstantSearch Hooks, this v7 documentation applies—just check for necessary changes. To continue using v6, you can find the archived documentation.
Signature
const router = createInstantSearchRouterNext({
  singletonRouter:  NextSingletonRouter,
  serverUrl?: string,
  beforeStart?: function,
  beforeDispose?: function,
  beforePopState?: function,
  routerOptions?: HistoryRouterOptions,
})

Import

JavaScript
import { createInstantSearchRouterNext } from "react-instantsearch-router-nextjs";

About this function

createInstantSearchNextRouter is a function that creates a Next.js-compatible InstantSearch router to pass to <InstantSearch> routing prop. It fixes some issues with the default router, such as the page not updating when using the browser’s back and forward buttons, or when navigating from a Next.js <Link> containing an InstantSearch query. It’s based on history so you can easily migrate from it by passing the same options to routerOptions.

Requirements

This function is available from the companion react-instantsearch-router-nextjs package.
You can’t use this function with getStaticProps. Use getServerSideProps or client-side rendering instead.

Examples

import {
  InstantSearch,
  InstantSearchSSRProvider,
  getServerState,
} from "react-instantsearch";

import { renderToString } from "react-dom/server";
import { createInstantSearchRouterNext } from "react-instantsearch-router-nextjs";
import singletonRouter from "next/router";

export default function SearchPage({ serverState, serverUrl }) {
  return (
    <InstantSearchSSRProvider {...serverState}>
      <InstantSearch
        searchClient={client}
        indexName="instant_search"
        routing={{
          router: createInstantSearchRouterNext({
            singletonRouter,
            serverUrl,
            routerOptions: {
              cleanUrlOnDispose: false,
            },
          }),
        }}
      >
        {/* Widgets */}
      </InstantSearch>
    </InstantSearchSSRProvider>
  );
}

export async function getServerSideProps({ req }) {
  const protocol = req.headers.referer?.split("://")[0] || "https";
  const serverUrl = `${protocol}://${req.headers.host}${req.url}`;
  const serverState = await getServerState(
    <SearchPage serverUrl={serverUrl} />,
    {
      renderToString,
    },
  );

  return {
    props: {
      serverState,
      serverUrl,
    },
  };
}

Parameters

singletonRouter
Next.SingletonRouter
required
The Next.js singleton router instance to use. It is the default export of next/router.
JavaScript
import singletonRouter from "next/router";

const router = createInstantSearchRouterNext({
  singletonRouter,
});
serverUrl
string
The URL of the page on the server. It is used by the router to determine the initial state of the search. Required only when using SSR.
JavaScript
export async function getServerSideProps({ req }) {
  const protocol = req.headers.referer?.split('://')[0] || 'https';
  const serverUrl = `${protocol}://${req.headers.host}${req.url}`;

  return {
    props: {
      serverUrl,
    },
  };
}

export default function SearchPage({ serverUrl }) {
  const router = createInstantSearchRouterNext({
    // ...
    serverUrl,
  });

  return (
    // InstantSearch components
  );
}
beforeStart
(onUpdate: () => void) => void
A function called before the router starts. You can use it to inform InstantSearch to update on router events by calling onUpdate. It is here for troubleshooting purposes or if you’re using a custom router with Next.js.
JavaScript
import singletonRouter from "next/router";

const router = createInstantSearchRouterNext({
  // ...
  beforeStart(onUpdate) {
    singletonRouter.events.on("routeChangeComplete", onUpdate);
  },
});
beforeDispose
() => void
A function called before the router gets disposed of. You can use it to detach event handlers you may have set up in beforeStart. It is here for troubleshooting purposes or if you’re using a custom router with Next.js.
JavaScript
import singletonRouter from "next/router";

let eventHandler;
const router = createInstantSearchRouterNext({
  // ...
  beforeStart(onUpdate) {
    eventHandler = onUpdate;
    singletonRouter.events.on("routeChangeComplete", eventHandler);
  },
  beforeDispose() {
    singletonRouter.events.off("routeChangeComplete", eventHandler);
  },
});
beforePopState
(options: object) => boolean
A function used by the Next.js router to know whether it should trigger SSR when using back/forward buttons. You can use it to override the default one by writing your own logic. The ownBeforePopState is the pre-existing handler that you may have set yourself, and the libraryBeforePopState is the default one from the library. It is here for troubleshooting purposes, you should not need to use it.Options contains the following properties:
  • state: NextHistoryState. The next state to apply.
  • ownBeforeState: BeforePopStateCallback. Either the default handler which just returns true, or the one you set yourself.
  • libraryBeforeState: BeforePopStateCallback. The default handler of the library which returns true if going on a different page, or false if staying on the same page.
JavaScript
const router = createInstantSearchRouterNext({
  // ...
  beforePopState({ state, ownBeforePopState, libraryBeforePopState }) {
    // You can compose your own logic, ignore the library one, it's up to you when you want to trigger SSR.
    return ownBeforePopState(state) && libraryBeforePopState(state);
  },
});
routerOptions
HistoryRouterOptions
You can pass options to the underlying history router. These will override the ones created by createInstantSearchRouterNext.You can check history for more information about the options.
JavaScript
const router = createInstantSearchRouterNext({
  // ...
  routerOptions: {
    createURL: // ...
    parseURL: ...
  },
});

Returns HistoryRouter

router
HistoryRouter
The router to pass to routing.
JavaScript
export default function SearchPage() {
  const routerNext = {
    router: createInstantSearchRouterNext({
      singletonRouter,
    }),
  };

  return (
    <InstantSearch
      searchClient={client}
      indexName="instant_search"
      routing={{ router: routerNext }}
    >
      {/*Widgets*/}
    </InstantSearch>
  );
}
I