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

# Routing and URL syncing in InstantSearch.js

> How to synchronize your URLs with InstantSearch.js.

export const Filter = () => <Tooltip tip="A filter is a condition that limits which records Algolia returns. Filters often use one or more facet-value pairs, such as brand:Apple AND color:red. You can also filter by numeric values, dates, tags, booleans, or geographic constraints." cta="Filtering" href="/doc/guides/managing-results/refine-results/faceting">
    filter
  </Tooltip>;

export const SearchQuery = () => <Tooltip tip="The text users enter into a search box. In the Search API, this corresponds to the query parameter. A search query is often used with filters, facets, and other parameters, but these aren't part of the query text itself.">
    search query
  </Tooltip>;

export const Records = () => <Tooltip tip="A record is a searchable object in an Algolia index. Each record consists of named attributes." cta="Algolia records" href="/doc/guides/sending-and-managing-data/prepare-your-data#algolia-records">
    records
  </Tooltip>;

export const FlavorSwitcher = ({current, baseHref = "", options = [], label = "InstantSearch framework"}) => {
  if (options.length === 0) {
    return <div className="not-prose" role="alert" style={{
      margin: "0.25rem 0 1.5rem",
      padding: "0.75rem",
      border: "1px solid #f59e0b",
      borderRadius: "0.625rem",
      color: "inherit",
      fontSize: "0.875rem"
    }}>
        FlavorSwitcher requires at least one option.
      </div>;
  }
  const selected = options.find(option => option.value === current) ?? options[0];
  return <div className="not-prose mint-flavor-switcher">
      <style>{`
        .mint-flavor-switcher {
          --mfs-bg: #ffffff;
          --mfs-bg-hover: #f4f4f5;
          --mfs-bg-current: #eef2ff;
          --mfs-border: #d4d4d8;
          --mfs-fg: #18181b;
          --mfs-muted: #71717a;
          --mfs-accent: #4f46e5;
          position: relative;
          width: min(100%, 19rem);
          margin: 0.25rem 0 1.5rem;
          color: var(--mfs-fg);
          font-size: 0.875rem;
          line-height: 1.25rem;
        }

        .dark .mint-flavor-switcher {
          --mfs-bg: #18181b;
          --mfs-bg-hover: #27272a;
          --mfs-bg-current: #272747;
          --mfs-border: #3f3f46;
          --mfs-fg: #fafafa;
          --mfs-muted: #a1a1aa;
          --mfs-accent: #a5b4fc;
        }

        .mint-flavor-switcher details {
          position: relative;
        }

        .mint-flavor-switcher summary {
          display: flex;
          min-height: 2.75rem;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          gap: 0.75rem;
          padding: 0.625rem 0.75rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          color: var(--mfs-fg);
          cursor: pointer;
          font-weight: 600;
          list-style: none;
          transition: border-color 150ms ease, box-shadow 150ms ease;
        }

        .mint-flavor-switcher summary::-webkit-details-marker {
          display: none;
        }

        .mint-flavor-switcher summary:hover {
          border-color: var(--mfs-accent);
        }

        .mint-flavor-switcher summary:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: 2px;
        }

        .mint-flavor-switcher__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .mint-flavor-switcher__chevron {
          flex: none;
          transition: transform 150ms ease;
        }

        .mint-flavor-switcher details[open] .mint-flavor-switcher__chevron {
          transform: rotate(180deg);
        }

        .mint-flavor-switcher__menu {
          position: absolute;
          z-index: 50;
          top: calc(100% + 0.375rem);
          left: 0;
          width: 100%;
          box-sizing: border-box;
          margin: 0;
          padding: 0.375rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          box-shadow: 0 12px 30px rgb(0 0 0 / 16%);
          list-style: none;
        }

        .mint-flavor-switcher__menu li {
          margin: 0;
          padding: 0;
        }

        .mint-flavor-switcher__option {
          display: grid;
          gap: 0.125rem;
          padding: 0.625rem 0.75rem;
          border-radius: 0.4rem;
          color: var(--mfs-fg);
          text-decoration: none;
        }

        .mint-flavor-switcher__option:hover {
          background: var(--mfs-bg-hover);
        }

        .mint-flavor-switcher__option:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: -2px;
        }

        .mint-flavor-switcher__option[aria-current="page"] {
          background: var(--mfs-bg-current);
          color: var(--mfs-accent);
        }

        .mint-flavor-switcher__name {
          font-weight: 600;
        }

        .mint-flavor-switcher__description {
          color: var(--mfs-muted);
          font-size: 0.8125rem;
        }

        @media (prefers-reduced-motion: reduce) {
          .mint-flavor-switcher summary,
          .mint-flavor-switcher__chevron {
            transition: none;
          }
        }
      `}</style>

      <details>
        <summary aria-label={`${label}: ${selected.label}`}>
          <span className="mint-flavor-switcher__label">{selected.label}</span>
          <svg className="mint-flavor-switcher__chevron" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="m6 9 6 6 6-6" />
          </svg>
        </summary>

        <ul className="mint-flavor-switcher__menu" aria-label={label}>
          {options.map(option => {
    const isCurrent = option.value === selected.value;
    const href = option.href ?? `${baseHref.replace(/\/$/, "")}/${encodeURIComponent(option.value)}`;
    return <li key={option.value}>
                <a className="mint-flavor-switcher__option" href={href} aria-current={isCurrent ? "page" : undefined}>
                  <span className="mint-flavor-switcher__name">
                    {option.label}
                  </span>
                  {option.description ? <span className="mint-flavor-switcher__description">
                      {option.description}
                    </span> : null}
                </a>
              </li>;
  })}
        </ul>
      </details>
    </div>;
};

<div className="mint-flavor-switcher-slot not-prose">
  <FlavorSwitcher
    current="js"
    baseHref="/doc/guides/building-search-ui/going-further/routing-urls"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
{ value: "vue", label: "Vue", description: "Vue InstantSearch" },
]}
  />
</div>

Synchronizing your UI with the browser URL is considered good practice.
It lets your users take one of your results pages, copy the URL, and share it.
It also improves the user experience by enabling the use of the back and next browser buttons to keep track of previous searches.

InstantSearch provides the necessary API entries to let you synchronize the state of your search UI (your refined widgets and current <SearchQuery />) with any kind of storage.

Use the [`routing`](/doc/api-reference/widgets/instantsearch/js#param-routing) option to synchronize UI state with the browser URL, so users can bookmark, share, and revisit a search.

This guide covers enabling default routing, customizing URLs, and creating SEO-friendly URLs.

<Note>
  Don't configure [`initialUiState`](/doc/api-reference/widgets/instantsearch/js#param-initial-ui-state) and `routing` together.

  * Use `initialUiState` to set the UI state when the search first loads, such as for a default query or filter.
  * Use `routing` to keep the UI state synchronized with the URL, so users can bookmark or share a search.
</Note>

## Default URLs

Set `routing` to `true` to use the default routing configuration:
a history router with simple state mapping.
This stores routing-compatible UI state in URL query parameters.

```js JavaScript icon=code theme={"system"}
const search = instantsearch({
  searchClient,
  indexName: "instant_search",
  routing: true,
});
```

Setting `routing` to `true` is equivalent to this configuration:

```js JavaScript icon=code theme={"system"}
const search = instantsearch({
  searchClient,
  indexName: "instant_search",
  routing: {
    router: instantsearch.routers.history(),
    stateMapping: instantsearch.stateMappings.simple(),
  },
});
```

Assume the following search UI state:

* **Query:** "galaxy"

* **Menu:**

  * `categories`: "Cell Phones"

* **Refinement List:**

  * `brand`: "Apple", "Samsung"

* **Page:** 2

This produces the following URL:

```txt theme={"system"}
https://example.org/?instant_search[query]=galaxy&instant_search[menu][categories]=Cell Phones&instant_search[refinementList][brand][0]=Apple&instant_search[refinementList][brand][0]=Samsung&instant_search[page]=2
```

By default, routing includes state from routing-compatible widgets.
With many widgets, this can create long URLs.
To create shorter or more descriptive URLs, customize the URL routing.

## Customize URL routing

You can customize which values appear and rename the URL parameters.

The `stateMapping` option maps between InstantSearch's `uiState` and the `routeState` used by the router.
Use it to rename parameters or omit values that you don't want to include in the URL.

```js JavaScript icon=code theme={"system"}
const search = instantsearch({
  searchClient,
  indexName: "instant_search",
  routing: {
    stateMapping: {
      stateToRoute(uiState) {
        // ...
      },
      routeToState(routeState) {
        // ...
      },
    },
  },
});
```

InstantSearch stores widget state in [`uiState`](/doc/api-reference/widgets/ui-state/js).
The following example maps that state to shorter URL parameters.

The state contains information about the user's search, including the query,
the <Filter /> selection,
the page being viewed,
and the widget hierarchy.
`uiState` only stores modified widget values, not defaults.

To persist this state in the URL,
InstantSearch converts the `uiState` into an object called `routeState`:
this `routeState` then becomes a URL.
Conversely, when InstantSearch reads the URL and applies it to the search,
it converts `routeState` into `uiState`.
This logic lives in two functions:

* `stateToRoute`: converts `uiState` to `routeState`.
* `routeToState`: converts `routeState` to `uiState`.

Assume the following search UI state:

* **Query:** "galaxy"

* **Menu:**

  * `categories`: "Cell Phones"

* **Refinement List:**

  * `brand`: "Apple" and "Samsung"

* **Page:** 2

This translates into the following `uiState`:

```json JSON icon="braces" theme={"system"}
{
  "indexName": {
    "query": "galaxy",
    "menu": {
      "categories": "Cell Phones"
    },
    "refinementList": {
      "brand": ["Apple", "Samsung"]
    },
    "page": 2
  }
}
```

Implement `stateToRoute` to flatten this object into a URL, and `routeToState` to restore the URL into a UI state:

```js JavaScript icon=code expandable theme={"system"}
const indexName = "instant_search";

const search = instantsearch({
  searchClient,
  indexName,
  routing: {
    stateMapping: {
      stateToRoute(uiState) {
        const indexUiState = uiState[indexName];
        return {
          q: indexUiState.query,
          categories: indexUiState.menu && indexUiState.menu.categories,
          brand:
            indexUiState.refinementList && indexUiState.refinementList.brand,
          page: indexUiState.page,
        };
      },
      routeToState(routeState) {
        return {
          [indexName]: {
            query: routeState.q,
            menu: {
              categories: routeState.categories,
            },
            refinementList: {
              brand: routeState.brand,
            },
            page: routeState.page,
          },
        };
      },
    },
  },
});
```

### Keep unrelated URL parameters

If you enable InstantSearch routing, the URL includes only parameters from widgets.
To keep other parameters unrelated to InstantSearch, add them when implementing `createURL`.

For example, to keep all URL parameters that start with `utm_`, use the following code:

```js JavaScript icon=code expandable theme={"system"}
history({
  // ... other options
  parseURL({ qsModule, location }) {
    return qsModule.parse(location.search.slice(1));
  },
  createURL({ qsModule, location, routeState }) {
    const { origin, pathname, hash } = location;

    const queriesFromUrl = qsModule.parse(location.search.slice(1));

    // Preserve unrelated URL parameters that start with "utm_".
    const utmQueries = Object.fromEntries(
      Object.entries(queriesFromUrl).filter(
        ([key]) =>
          !Object.keys(routeState).includes(key) &&
          // Add here a condition to keep the parameters you want, for example starting with "utm_"
          key.startsWith("utm_"),
      ),
    );

    // Combine InstantSearch state with the preserved parameters.
    const queryString = qsModule.stringify(
      {
        ...routeState,
        ...utmQueries,
      },
      {
        addQueryPrefix: true,
        arrayFormat: "repeat",
      },
    );

    return `${origin}${pathname}${queryString}${hash}`;
  },
});
```

## SEO-friendly URLs

To create more descriptive URLs, move search state from query parameters into the URL path.
This is a common pattern for ecommerce category and search pages.

```txt theme={"system"}
https://example.org/search/Cell+Phones/?query=galaxy&page=2&brands=Apple&brands=Samsung
```

### Store categories in the URL path

This example stores the category in the path and the query, page, and brands as query parameters.

```js JavaScript icon=code expandable theme={"system"}
// Convert a category name to a URL slug.
// Replace spaces with "+" and encode other characters.
function getCategorySlug(name) {
  return name.split(" ").map(encodeURIComponent).join("+");
}

// Convert a category slug to a category name.
// Replace "+" with spaces and decode other characters.
function getCategoryName(slug) {
  return slug.split("+").map(decodeURIComponent).join(" ");
}

const search = instantsearch({
  searchClient,
  indexName: "instant_search",
  routing: {
    router: instantsearch.routers.history({
      windowTitle({ category, query }) {
        const queryTitle = query ? `Results for "${query}"` : "Search";

        if (category) {
          return `${category} – ${queryTitle}`;
        }

        return queryTitle;
      },

      createURL({ qsModule, routeState, location }) {
        const urlParts = location.href.match(/^(.*?)\/search/);
        const baseUrl = `${urlParts ? urlParts[1] : ""}/`;

        const categoryPath = routeState.category
          ? `${getCategorySlug(routeState.category)}/`
          : "";
        const queryParameters = {};

        if (routeState.query) {
          queryParameters.query = encodeURIComponent(routeState.query);
        }
        if (routeState.page !== 1) {
          queryParameters.page = routeState.page;
        }
        if (routeState.brands) {
          queryParameters.brands = routeState.brands.map(encodeURIComponent);
        }

        const queryString = qsModule.stringify(queryParameters, {
          addQueryPrefix: true,
          arrayFormat: "repeat",
        });

        return `${baseUrl}search/${categoryPath}${queryString}`;
      },

      parseURL({ qsModule, location }) {
        const pathnameMatches = location.pathname.match(/search\/(.*?)\/?$/);
        const category = getCategoryName(
          (pathnameMatches && pathnameMatches[1]) || "",
        );
        const {
          query = "",
          page,
          brands = [],
        } = qsModule.parse(location.search.slice(1));
        // `qs` does not return an array when there's a single value.
        const allBrands = Array.isArray(brands)
          ? brands
          : [brands].filter(Boolean);

        return {
          query: decodeURIComponent(query),
          page,
          brands: allBrands.map(decodeURIComponent),
          category,
        };
      },
    }),

    stateMapping: {
      stateToRoute(uiState) {
        const indexUiState = uiState["instant_search"] || {};

        return {
          query: indexUiState.query,
          page: indexUiState.page,
          brands:
            indexUiState.refinementList && indexUiState.refinementList.brand,
          category: indexUiState.menu && indexUiState.menu.categories,
        };
      },

      routeToState(routeState) {
        return {
          instant_search: {
            query: routeState.query,
            page: routeState.page,
            menu: {
              categories: routeState.category,
            },
            refinementList: {
              brand: routeState.brands,
            },
          },
        };
      },
    },
  },
});
```

This example uses [`instantsearch.routers.history`](/doc/api-reference/widgets/history-router/js) to configure the default history router.
The router reads and writes URLs, while `stateMapping` maps `uiState` to `routeState` and back.

When you configure the history router, you can customize these functions:

* `windowTitle`: returns the browser window title for a `routeState`.
* `createURL`: creates a URL from `routeState`. InstantSearch calls it when synchronizing the browser URL, rendering links in the `menu` widget, or when a connector calls `createURL`.
* `parseURL`: creates `routeState` from the URL when users load or reload the page or use the browser's back or forward navigation.

### Make URLs more discoverable

Shorter category URLs can be more readable and memorable.
Use a mapping object to map category names to shorter URL slugs.

Given the dataset in this guide, you can make some categories more discoverable:

* "Cameras and camcorders" → `/Cameras`
* "Car electronics and GPS" → `/Cars`

When users open `https://example.org/search/Cameras`, InstantSearch selects the "Cameras and camcorders" category.

Define mappings between category names and URL slugs:

```js JavaScript icon=code expandable theme={"system"}
// Map URL slugs to category names.
const encodedCategories = {
  Cameras: "Cameras and camcorders",
  Cars: "Car electronics and GPS",
  Phones: "Phones",
  TV: "TV and home theater",
};

// Map category names to URL slugs.
const decodedCategories = Object.keys(encodedCategories).reduce((acc, key) => {
  const newKey = encodedCategories[key];
  const newValue = key;

  return {
    ...acc,
    [newKey]: newValue,
  };
}, {});

// Use the mappings when converting category names and slugs.
function getCategorySlug(name) {
  const encodedName = decodedCategories[name] || name;

  return encodedName.split(" ").map(encodeURIComponent).join("+");
}

function getCategoryName(slug) {
  const decodedSlug = encodedCategories[slug] || slug;

  return decodedSlug.split("+").map(decodeURIComponent).join(" ");
}
```

You can build these dictionaries from your Algolia <Records />.

With such a solution, you have full control over what categories are discoverable from the URL.

### About SEO

For your search results to be part of a public search engine's results, you must be selective.
Trying to index too many search results pages could be considered spam.

To do that, create a [`robots.txt`](http://www.robotstxt.org/) and host it at `https://example.org/robots.txt`.

Here's an example based on the URL scheme you created.

```txt robots.txt theme={"system"}
User-agent: *
Allow: /search/Audio/
Allow: /search/Phones/
Disallow: /search/
Allow: *
```

<Columns>
  <Card title="Basic routing demo" icon="box" href="https://codesandbox.io/s/github/algolia/doc-code-samples/tree/master/instantsearch.js/routing-basic">
    Explore basic InstantSearch routing in CodeSandbox.
  </Card>

  <Card title="SEO-friendly routing demo" icon="box" href="https://codesandbox.io/s/github/algolia/doc-code-samples/tree/master/instantsearch.js/routing-seo-friendly">
    Explore SEO-friendly routing in CodeSandbox.
  </Card>
</Columns>

## Group facet values

To group facet values such as "turquoise", "ocean", and "sky" under "blue", add the group at indexing time.
Either add a separate grouping attribute or store both the individual value and group value in the same attribute.

For example, with the following dataset:

```json JSON icon=braces theme={"system"}
[
  {
    "objectID": "1",
    "color": "turquoise"
  },
  {
    "objectID": "2",
    "color": "ocean"
  },
  {
    "objectID": "3",
    "color": "sky"
  }
]
```

To facet on a separate grouping attribute, add `colorGroup` to each record:

```json JSON icon=braces theme={"system"}
[
  {
    "objectID": "1",
    "color": "turquoise",
    "colorGroup": "blue"
  },
  {
    "objectID": "2",
    "color": "ocean",
    "colorGroup": "blue"
  },
  {
    "objectID": "3",
    "color": "sky",
    "colorGroup": "blue"
  }
]
```

To facet on both individual colors and their group, store both values in the `color` attribute:

```json JSON icon=braces theme={"system"}
[
  {
    "objectID": "1",
    "color": ["turquoise", "blue"]
  },
  {
    "objectID": "2",
    "color": ["ocean", "blue"]
  },
  {
    "objectID": "3",
    "color": ["sky", "blue"]
  }
]
```
