Public API for the prefetch scheduler (custom prefetching via `link:prefetch`) · Issue #36655 · nuxt/nuxt · GitHub
Skip to content

Public API for the prefetch scheduler (custom prefetching via link:prefetch) #36655

Description

@ChronicStone

Describe the feature

Hey! The new prefetch scheduler in 4.6 is very cool. Could we get a public API for it, so custom prefetching hooked on link:prefetch can go through it too?

Here's my use case, simplified. Our pages load data with TanStack Query, and each page declares which queries it needs:

// pages/product/[id].vue
definePageMeta({
  queryPrefetch: (route) => [productQuery(route.params.id)],
})

A plugin warms the cache when a link gets prefetched:

export default defineNuxtPlugin((nuxtApp) => {
  const router = useRouter()
  const queryClient = useQueryClient()

  nuxtApp.hook('link:prefetch', (url) => {
    const route = router.resolve(url)
    for (const query of route.meta.queryPrefetch?.(route) ?? []) {
      queryClient.prefetchQuery(query)
    }
  })
})

Right now these requests go out right away, outside the scheduler, so they don't get the throttling, deduplication or cancellation on navigation. It works if I use usePrefetchScheduler and prefetchGroup from #app/internal/*, but those are internal:

import { usePrefetchScheduler } from '#app/internal/prefetch-scheduler'
import { prefetchGroup } from '#app/internal/prefetch-util'

usePrefetchScheduler().schedule({
  key: `query:${url}`,
  priority: 'payload',
  scope: 'navigation',
  group: prefetchGroup(url), // keeps the prefetch alive when navigating to that page
  run: (signal) => {
    signal.addEventListener('abort', () => queryClient.cancelQueries(/* ... */))
    return Promise.all(queries.map((query) => queryClient.prefetchQuery(query)))
  },
})

A public version of this would be great.

Additional information

  • Would you be willing to help implement this feature?
  • Could this feature be implemented as a module?

Final checks

  • Read the contribution guide.
  • Check existing discussions and issues.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions