Next.js Discord

Discord Forum

How to set up flexsearch?

Unanswered
Indian mackerel posted this in #help-forum
Open in Discord
Indian mackerelOP
Im trying to implement a local search feature using flexsearch. However, I couldnt find anything online on how to do it in nextjs. My first naive approach was to instantiante an instance of Flexsearch.Index in the root layout, and pass it on to the relevant components as props, but im (naturally) getting errors as passing classes is not possible between server and client components. Passing a callback function for index.search also doesnt work for the same reason.

second approach im trying is to instantiate the index on a module level and import it in the components that use it.
Like so:
/search.ts const index: Index = new Index(); //instantiate index on module level -> should persist through lifetime of server export const createIndex = (services: Service[]) => { services.forEach((service) => { index.add(service.id, service.name, ); }); }; export const searchIndex = (query: string) => { return index.search(query); }; export default index;

and in the root layout:
async function Page({ params: { lang } }: { params: { lang: string } }) { // fetch server side data const services = await fetchServices(lang); if (services) createIndex(services); //populate index with fetched services return ( <div > <SearchBar/> </div> ); } export default Page;

and finally in the SearchBar component, I search:
'use client'; const SearchBar: FC<Props> = ({... }) => { function onChange(query:string) { const result = searchIndex(query); } return ... }

However, the results are always empty. indicating that the index is not persisted (my guess) and maybe just re-instantiated. I also tried calling the search function through an API route with the same result.

Could anyone point me in the right direction? Not rly sure what i'm supposed to do here. thanks!

0 Replies