> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# createInstantSearchRouterNext

> Creates a Next.js-compatible router for InstantSearch.

<Note>
  This is the **React InstantSearch v7** documentation.
  If you're upgrading from v6, see the [upgrade guide](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-v6-to-react-instantsearch-v7).
  If you were using React InstantSearch Hooks,
  this v7 documentation applies—just check for [necessary changes](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-hooks-to-react-instantsearch-v7).
  To continue using v6, you can find the [archived documentation](https://algolia.com/old-docs/deprecated/instantsearch/react/v6/api-reference/instantsearch/).
</Note>

```ts Signature theme={"system"}
const router = createInstantSearchRouterNext({
  singletonRouter:  NextSingletonRouter,
  serverUrl?: string,
  beforeStart?: function,
  beforeDispose?: function,
  beforePopState?: function,
  routerOptions?: HistoryRouterOptions,
})
```

## Import

```js JavaScript icon=code theme={"system"}
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>`](/doc/api-reference/widgets/instantsearch/react) [`routing`](/doc/api-reference/widgets/instantsearch/react#param-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`](/doc/api-reference/widgets/history-router/react)
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`](https://github.com/algolia/instantsearch/tree/master/packages/react-instantsearch-router-nextjs) package.

<Warning>
  You can't use this function with [`getStaticProps`](https://nextjs.org/docs/pages/api-reference/functions/get-static-props).
  Use `getServerSideProps` or client-side rendering instead.
</Warning>

## Examples

<CodeGroup>
  ```jsx With SSR theme={"system"}
  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,
      },
    };
  }
  ```

  ```jsx Without SSR theme={"system"}
  import { InstantSearch } from "react-instantsearch";
  import { createInstantSearchRouterNext } from "react-instantsearch-router-nextjs";
  import singletonRouter from "next/router";

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

## Parameters

<ParamField body="singletonRouter" type="Next.SingletonRouter" required>
  The Next.js singleton router instance to use.
  It is the default export of `next/router`.

  ```js JavaScript icon=code theme={"system"}
  import singletonRouter from "next/router";

  const router = createInstantSearchRouterNext({
    singletonRouter,
  });
  ```
</ParamField>

<ParamField body="serverUrl" type="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.

  ```js JavaScript icon=code theme={"system"}
  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
    );
  }
  ```
</ParamField>

<ParamField body="beforeStart" type="(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.

  ```js JavaScript icon=code theme={"system"}
  import singletonRouter from "next/router";

  const router = createInstantSearchRouterNext({
    // ...
    beforeStart(onUpdate) {
      singletonRouter.events.on("routeChangeComplete", onUpdate);
    },
  });
  ```
</ParamField>

<ParamField body="beforeDispose" type="() => 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.

  ```js JavaScript icon=code theme={"system"}
  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);
    },
  });
  ```
</ParamField>

<ParamField body="beforePopState" type="(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.

  ```js JavaScript icon=code theme={"system"}
  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);
    },
  });
  ```
</ParamField>

<ParamField body="routerOptions" type="HistoryRouterOptions">
  You can pass options to the underlying history router.
  These will override the ones created by `createInstantSearchRouterNext`.

  You can check [`history`](/doc/api-reference/widgets/history-router/react) for more information about the options.

  ```js JavaScript icon=code theme={"system"}
  const router = createInstantSearchRouterNext({
    // ...
    routerOptions: {
      createURL: // ...
      parseURL: ...
    },
  });
  ```
</ParamField>

## Returns HistoryRouter

<ParamField body="router" type="HistoryRouter">
  The router to pass to [routing](/doc/api-reference/widgets/instantsearch/react#param-routing).

  ```jsx JavaScript icon=code theme={"system"}
  export default function SearchPage() {
    const routerNext = {
      router: createInstantSearchRouterNext({
        singletonRouter,
      }),
    };

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