DEV Community

Cover image for Fixing a Search Race Condition in npmx
Anil Loutombam
Anil Loutombam

Posted on

Fixing a Search Race Condition in npmx

Summer Bug Smash: Clear the Lineup 🐛🛹

This is a submission for DEV's Summer Bug Smash: Clear the Lineup powered by Sentry.

Project Overview

npmx is a modern browser for the npm registry. It provides package search, version timelines, dependency information, comparisons, and other tools for exploring npm packages.

Bug Fix or Performance Improvement

I worked on a search bug reported in issue #2617.

When the saved page size was 50 or higher and instant search was disabled, the first search could show no package results. The organization suggestion still appeared, and reloading the same search page made all the package results appear.

That made it clear that the packages existed and the request was working, but something was going wrong while the search page was being initialized.

Code

Pull request: npmx-dev/npmx.dev#3109

The fix waits for an initial search that is already in progress:

if (asyncData.status.value === 'pending') {
  await asyncData.refresh({ dedupe: 'defer' })
}
Enter fullscreen mode Exit fullscreen mode

My Improvements

The page-size preference is stored locally. During the first navigation to the search page, the search could start with the default size of 25. The saved preference would then load and change the requested size to 50 while that search was still pending.

This triggered fetchMore before the initial response was ready. It could read the temporary empty response and store it in the search cache. The completed response arrived afterward, but the empty cached value took priority, so the page displayed no packages.

I updated fetchMore to wait for the pending search before reading its result. I used dedupe: 'defer' so it joins the request already in progress instead of cancelling it and starting another one.

I also added a regression test that changes the requested page size while the initial Algolia search is pending. The test verifies that the completed package results are preserved.

After the fix, the package results appear on the first search without requiring a reload.

Top comments (0)