UI libraries / React InstantSearch / Widgets

createInstantSearchRouterNext()

This is the React InstantSearch v7 documentation. React InstantSearch v7 is the latest version of React InstantSearch and the stable version of React InstantSearch Hooks.

If you were using React InstantSearch v6, you can upgrade to v7.

If you were using React InstantSearch Hooks, you can still use the React InstantSearch v7 documentation, but you should check the upgrade guide for necessary changes.

If you want to keep using React InstantSearch v6, you can find the archived documentation.

Signature
const router = createInstantSearchRouterNext({
  singletonRouter:  NextSingletonRouter,
  serverUrl?: string,
  beforeStart?: function,
  beforeDispose?: function,
  beforePopState?: function,
  routerOptions?: HistoryRouterOptions,
})
Import
1
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 a number of 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 is based on history so you can easily migrate from it by passing the same options to routerOptions.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
type: Next.SingletonRouter
Required

The Next.js singleton router instance to use. It is the default export of next/router.

1
2
3
4
5
import singletonRouter from 'next/router';

const router = createInstantSearchRouterNext({
  singletonRouter,
});
serverUrl
type: string
Required on the server

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
type: (onUpdate: () => void) => void
Optional

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.

1
2
3
4
5
6
7
8
import singletonRouter from 'next/router';

const router = createInstantSearchRouterNext({
  // ...
  beforeStart(onUpdate) {
    singletonRouter.events.on('routeChangeComplete', onUpdate);
  },
});
beforeDispose
type: () => void
Optional

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
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
type: (options: object) => boolean
Optional

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.
1
2
3
4
5
6
7
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
type: HistoryRouterOptions
Optional

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.

1
2
3
4
5
6
7
const router = createInstantSearchRouterNext({
  // ...
  routerOptions: {
    createURL: // ...
    parseURL: ...
  },
});

Returns
HistoryRouter

router
type: HistoryRouter

The router to pass to routing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export default function SearchPage() {
  const routerNext = {
    router: createInstantSearchRouterNext({
      singletonRouter,
    }),
  };

  return (
    <InstantSearch
      searchClient={client}
      indexName="instant_search"
      routing={{ router: routerNext }}
    >
      {/* Widgets */}
    </InstantSearch>
  );
}
Did you find this page helpful?
React InstantSearch v7