instantsearch: Instantsearch hooks: router not getting along with Next.JS
We are trying out a server rendered search implementation with NextJS. All seems okay until we try to add a routing object to InstantSearch. We are using routing to have urls for our search state, and to make them SEO friendly (q=potato&type=tuber). There are all sorts of quirks though, from additional re-renders on load to the rest of the application routing breaking.
1. Re-Render Example:
If we try starting at url /search?q=potato
we immediately see a re-render to /search
.
2. Routing Example:
When we click on a hit/result <Link href={
/post/${hit.slug}>š„ hit</Link>
we are taken to our expected /post/${hit.slug}
url, but then from there our routing in general seems to be broken. Clicking back moves to /search?q=potato
, but only the url changes. Page content is not updated.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 35
- Comments: 87 (29 by maintainers)
Commits related to this issue
- feat: nextjs algolia ssr routing workaround The NextRouterHandler is a workaround for a current limitation in algolia instantsearch.js * https://github.com/algolia/react-instantsearch/iss... — committed to elasticpath/d2c-starter-kit by field123 2 years ago
- feat: search page routing (#35) * feat: PLP with Algolia * feat: added algolia to All Prodicts page * refactor: extracted search components * refactor: instantsearch is now scoped Scoping... — committed to elasticpath/d2c-starter-kit by field123 2 years ago
- feat: category pages style (#37) * feat: PLP with Algolia * feat: added algolia to All Prodicts page * refactor: extracted search components * refactor: instantsearch is now scoped Scopin... — committed to elasticpath/d2c-starter-kit by field123 2 years ago
Need this. Iām pretty frustrated after 2 years of developing nextJS applications with algolia that this hasnāt been addressed.
Algolia team, just want to chime in here in the event anyone is listening to this thread. Native support for this issue really critical. Can you please provide an update on where this fix is on the roadmap and when it can be expected, if ever?
@dhayab do we have an ETA for the native support solution? by that I mean 3rd party routing going along with Algolia InstantSearch
Maybe to have like an example working with NextJS, including SSG, SSR and CSR. The user flow would be like that land on a category (SSG) => facet click to filtered category(SSR) => and for example change sorting (CSR)
Itās a temporary solution until we finish implementation and ship native support for third-party router later this year.
Algolia, when will the solution be released? No one is responsible? Hey, it is something criticalā¦
Hi @Haroenv thanks for the response. And yes, no doubt, def not a simple problem keeping the state and router in sync. Its feels so close š ! Iāve forked your sandbox to demonstrate item 2 (Routing example above)ā¦
https://codesandbox.io/s/hooks-next-bug-3506-item-2-6ekug6?file=/pages/index.tsx
To reproduceā¦
Perhaps issue is something to do with how the InstantSearch component / router is unmounted.
Hi everyone ! šāāļø
First of all, thank you for your patience and for providing precious feedback.
Our solution for creating a Next.js compatible router for InstantSearch is now generally available and published on npm as
react-instantsearch-hooks-router-nextjs
. It has to be a separate package as it hasnext
as apeerDependency
.Its documentation is available on the Algolia docs right there : https://www.algolia.com/doc/api-reference/widgets/instantsearch-next-router/react-hooks/
You can also see it in action on CodeSandbox : https://codesandbox.io/s/github/algolia/instantsearch/tree/master/examples/react-hooks/next-routing
If youāre seeing any problem still, please raise another issue with a reproduction and make sure to check that itās not just related to back button press, try to see if reloading the page raises the same issue. If youāre also on a dynamic route, check that the issue is not caused by components/hooks being unmounted.
Thanks again to all of you !
Any progress on a native solution? Thanks!
Hi @francoischalifour , iām still experiencing the 2 issues mentioned by @dsbrianwebster (iām using nextjs 12 & react 17), especially the broken back button
Hi all, we are currently working on a solution, and we came up with the idea of a package that lets you create a custom router that is compatible with Next.js and fixes the back button issue as well as the dynamic routing issue.
It needs to be its own package because it has
next
as apeerDependency
so we can use its router.Before moving forward weād appreciate getting your feedback. For this we released this experimental package
instantsearch-router-next-experimental
Please note that as its name implies, this one should only be used for testing. If the solution is validated a new packaged with a definitive name and API will get published.To use it, install it :
Then you can instantiate it and pass it in the
routing
prop of the<InstantSearch>
component :If you are not using SSR therefore not having a
url
prop, you can simply callcreateInstantSearchNextRouter
without any argument. And if you have custom routing methods such ascreateUrl
orparseUrl
you may pass them in the object argument as well. You can find more info about usage on the npm pageYou may find the source code in the package itself or on this branch.
Weāre looking forward to hearing how it works for you. It can be a reaction to this comment if it works nicely for you, or a comment detailing which version of
next
andreact-instantsearch-hooks
you are using if it does not work !Thanks š
Thanks @dhmacs, I used that workaround for the moment, triggering a page reload once the popstate occurs over the search page. Something simple like this for the moment, until issue is fixed:
@Raesta : we want to gather as much feedback as possible to make sure it covers most issues and versions, so it should come out in around 1 month from now
@colis : I canāt seem to reproduce the issue on my end, there might be some specific routing ? A reproduction of the issue on codesandbox would help greatly
Hi @wenche, thanks again for the replies ! I totally agree, weāll further iterate on how
InstantSearch
cleans up after unmounting, as this problem could impact other middlewares as well. It should be good by the time the official package is released š@joshgeller Sorry for the lack of clarity, what I meant is that it would be nice to make that
onUpdate
part of the api.FYI: Iāve copied the original
history.ts
into my repo and made some adjustments in order to use the nextjs router instead - it certainly hasnāt been cleaned up but feel free to take a look here: https://gist.github.com/klaasman/b0e06e8f63dbae70829424232285570c@colis : After some intense debugging session I found out that when reloading the page with the initial query,
removeWidgets
gets called on thetaxonomies.auction_tax.name
refinement list which makes InstantSearch cleanup the state thus resetting the query. So you have to make sure your<RefinementList>
oruseRefinementList
is mounted once and not unmounted later. It most likely doesnāt have anything to do with Next.js or the router. Thereās something important to know when using React InstantSearch Hooks, itās that unmounting a widget component or hook cleans up its state. Which means if you do conditional rendering you have to be very careful. Thereās a guide for you to know more about it : https://www.algolia.com/doc/guides/building-search-ui/widgets/show-and-hide-widgets/react-hooks/@osseonews : Itās coming out this month ! Weāll make an announcement on this issue when itās the case š
@osseonews : Yes this is fixed in the package ! Using a simple
<a>
tag does work but it beats the purpose of making Single Page Apps, for example you will lose thealgoliasearch
cache so any subsequentback
button click will trigger a request to Algolia again.@Raesta : I will need a reproduction to help please, can be a Codesandbox or a repo. Are you using a custom
createURL
? This normally shouldnāt ever returnnull
.Hi, Iām also still experiencing issue number 2, mentioned by @dsbrianwebster (iām using nextjs 12 & react 18). Has anyone come up to a solution? The custom router implementation maybe? Thanks
I also have this warning:
And when I switch pages in Next like this:
Its crashing in the instantsearch clean up:
Here is a snippet of line 530
package.json:
Everything works as expected until we start using sorting. As soon as we use sorting and hit a product the browser back button does not work anymore. Filtering works as expected.
@adesege do you have a reproduction? the example in the repo is using a dynamic path
When using the back button from a page not using InstantSearch to my InstantSearch page, every facet is removed from the url (and from the state). Is it the expected behavior ?
@aymeric-giraudet Works perfectly for my use case and just pushed it to production š
@LefanTan : Yes itās a known limitation of
getServerState
, since itās not rendered by Next.js it does not have access to its router souseRouter
returnsnull
. Iāll make note of it for us to add disclaimers but to circumvent it you should maybe avoid usinguseRouter
directly and you could maybe wrap it into a custom hook that returns a stub object whenuseRouter
returnsnull
.@wenche : Thanks for the reproduction ! I see you have
reactStrictMode: true
, these bugs indeed do happen on strict mode while in development mode. The component mounts twice, and it seems like the router middleware does not get unsubscribed on first unmount, so the router tries tosetUiState
on the first instance which is stale. I will look for a way for InstantSearch to properly recreate the router.Unfortunately, we see some more issues when we use this new library. We have created an example repository to highlight our findings (Let me know if you need our Algolia app id and the api key ).
Disclaimer: Some of these issues might have the same root cause, but itās not easy to find a way to explain without too much confusion. Thatās why I tried to split it up š
Steps to reproduce issue no1
?Data_Set%5Bquery%5D=data
Click this link namedTake me to the search!
Steps to reproduce issue no2
The UI state for the index "Data_Set" is not consistent with the widgets mounted.
warning in the consoleSteps to reproduce issue no3
data
Plot twist If we use the
onStateChange
function, issue no1 and no3 seems to work.These findings are in addition to the one already mentioned above with the clean up issue š
Thank you for fixing the issue, but
getServerState
doesnāt seem to know how to handlerouter
during SSR like NextJS does?This is the errors Iām getting on everywhere that uses next/router:
@avremel
Even if you donāt put a
<title>
tag in<Head>
it does override with an empty value when routerāspush
is called šFor now I would suggest either removing
Head
completely if you can, otherwise withuseRef
you can store the created title inwindowTitle
and use it as a child for<Head><title>...</title></Head>
Iāll look for other solutions for the definitive package š
@aymeric-giraudet Thank you for the package! Very helpful to inspect the route as a drop in replacement for uiState which IME is unreliable (see here).
Iāve noticed that
windowTitle
doesnāt seem to work. It flashes the new title for a second and then reverts back to the old one.Iāve provided custom routing functions:
Hi @aymeric-giraudet work perfectly, thanks a lot for your work.
When do you think the final package will be published?
Hi @Raesta,
Sorry for the double post but it should be fixed by now, with version
0.0.5
What I did is I added this line topackage.json
ininstantsearch-router-next-experimental
:To instruct webpack to use
cjs
even ifmjs
is available, and it seems to fix things.You can let me know if this fixes things on your end too, thanks ! š
I also needed this and figured out how to do this until thereās official support. Itās a bit hacky but it works for my use case.
Hereās the router code (I suggest you put it in a
.js
file):Use it like so:
The
url
comes fromgetServerSideProps
and is used for SSR like so:Hi, hereās a sandbox with another workaround that shares some similarities with @JulesVerdijk : https://codesandbox.io/s/rish-next-router-handler-is22ev?file=/pages/[category].tsx.
It consists of a
useNextRouterHandler()
Hook that returns:initialUiState
that needs to be passed to<InstantSearch>
(for SSR)<NextRouterHandler />
empty component that should be mounted in<InstantSearch>
(to be able to use Hooks from React InstantSearch Hooks)It required an explicit definition of the route/state mapping, and supports Next.js dynamic routes (by specifying the route query to inject).
I tested it on some sandbox shared in the issues, and it works well. Feel free to share below if there are edge cases that are not handled by this workaround.
I ran into this problem as well and created a, pretty hacky, fix that seems to work (not used in production yet, so fingers crossed). What I did was taking full control of the routing, not using the router provided by Instantsearch.
Requirement for this solution is a helper that can convert an UiState to a URL (like the createURL function in the algolia router) and back again (like the parseURL function).
In basis the solution works like this:
So you now control the updating of the UiState yourself, and use this to update the NextRouter accordingly. However this is not enough, it works one way only. On
onStateChange
the route changes, but if you route through Next (e.g. press the back button) the UiState does not update accordingly. To be able to do this you need to be able to setUiState on a routing event, butInstantSearch
does not propegate asetUiState
function outside of theonStateChange
prop (can we please get that Algolia?). However, this function Ćs available in child-components in theuseInstantSearch
hook. I abused this to set the UiState based on routing changes, something like this:Note that I pass
uiStateFromAlgolia
as a prop toUpdateStateBasedOnRoute
, but it is also available fromuseInstantSearch
however I found passing it made it update more smoothly (it is a hacky solution!). With again a disclaimer that this works in a development environment but I havenāt used it in production yet.This would work a lot more smoothly if we could actually get a
setUiState
prop directly onInstantSearch
so this can all be controlled within the main component instead of in an empty child component.@dhayab posted a workaround using Next useRouter and useEffect in a discussion. Worked for me š
https://github.com/algolia/react-instantsearch/discussions/3376#discussioncomment-2297218
You can provide a custom router, you donāt need to use
history
, the methods are described here https://www.algolia.com/doc/api-reference/widgets/instantsearch/js/#widget-param-routingIād advise looking at the implementation of the history router, because thereās some edge cases we already cover there as a base
Iām running into issue no. 2 here as well, the broken back button. I think itās caused by the instantsearch.js history implementation performing itās own history mutations, over here:
https://github.com/algolia/instantsearch.js/blob/0a517609de103eef4f8edfefe6e28a1d79a14209/src/lib/routers/history.ts#L142
e.g., try the following on any app rendered by next.js (in this example Iāll use https://nextjs.org/)
history.pushState({}, '', '/test-foo-bar')
and see the url get updated to the new pathname. (this mimics an updated url due to filtering)/showcase
to/test-foo-bar
, in the UI nothing happens, youāll stay on the āshowcaseā page.~The algolia hook history API needs something like custom routing method in order to fix this.~
~e.g. calling context:~
~When an
onUpdate
is provided the history instance should obviously no more do itās own history mutations.~~This also alllows us to perform a
history.replace()
instead ofhistory.push()
which makes more sense in some filtering contexts.~Edit: the above is already possible with a custom history handler as suggested below.
Hey @dsbrianwebster ā this is likely because Next.js is using Strict Mode, which isnāt yet supported in the library with React 18.
Our
<InstantSearch>
component reads the URL query params to set the initial state, and write the browser URL on unmount to reset it. This is a first-class behavior of the underlying InstantSearch.js library. The problem is that during the second Strict Mode render, the URL has been reset, and therefore the second render is unable to recover the initial state. This breaks URL synchronization.Weāre working on React 18 Strict Mode support this week so you can expect a fix in the coming days.
In the mean time, could you disable Strict Mode on the
<InstantSearch>
component?Edit: Strict Mode support was introduced in v6.28.0.