question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Resource preloaded was not used by SWR

See original GitHub issue

Bug report

Description / Observed Behavior

When using <link rel='preload' /> prefetching, the following warning occurs in Mozilla Firefox 87.0 (on Pop_OS! 20.04):

The resource at “http://localhost:3000/api/account” preloaded with link preload was not used within a few seconds. Make sure all attributes of the preload tag are set correctly.

Expected Behavior

SWR should use the prefetched data and that warning should not occur. I’m guessing that the reason why the data wasn’t used by SWR is because I’m using axios (which, in turn, uses XMLHttpRequest) in my SWR fetcher function (instead of using the browser built-in fetch function). If this is the case, you should definitely add it to the documentation.

Repro Steps / Code Example

I followed the docs on preloading data and added the following:

<Head>
  <link rel='preload' href='/api/account' as='fetch' />
</Head>

I then use SWR to fetch that data client-side (using axios which uses XMLHttpRequest under the hood):

const { data } = useSWR<UserJSON>('/api/account', fetcher);

That fetcher function is defined as the following:

export async function fetcher<T, D = T>(
  url: string,
  method: 'get' | 'put' | 'post' | 'patch' | 'delete' = 'get',
  data?: D
): Promise<T> {
  const headers: Record<string, string> = {};
  if (typeof data === 'string') headers['Content-Type'] = 'text/plain';
  const [err, res] = await to<AxiosResponse<T>, AxiosError<APIErrorJSON>>(
    axios({ method, url, data, headers })
  );
  if (err && err.response) {
    const msg = `API (${url}) responded with error: ${err.response.data.message}`;
    throw new APIError(msg, err.response.status);
  } else if (err && err.request) {
    throw new APIError(`API (${url}) did not respond.`);
  } else if (err) {
    throw new APIError(`${err.name} calling API (${url}): ${err.message}`);
  }
  return (res as AxiosResponse<T>).data;
}

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
koba04commented, Jun 22, 2021

@nicholaschiang The example in the documentation has a crossorigin attribute, but your code doesn’t.

<link rel="preload" href="/api/data" as="fetch" crossorigin="anonymous">

https://swr.vercel.app/docs/prefetching#top-level-page-data

I think the crossorigin attribute is necessary to preload a fetch request.

When preloading resources that are fetched with CORS enabled (e.g. fetch(), XMLHttpRequest or fonts), special care needs to be taken to setting the crossorigin attribute on your <link> element. The attribute needs to be set to match the resource’s CORS and credentials mode, even when the fetch is not cross-origin.

https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/preload#cors-enabled_fetches

2reactions
shudingcommented, Jun 18, 2022

We now have a preload API in SWR that covers this case better, check out the release: https://github.com/vercel/swr/releases/tag/2.0.0-beta.4

It will be documented with the upcoming 2.0 stable release.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Prefetching Data - SWR
SWR provides the preload API to prefetch the resources programmatically and store the results in the cache. preload accepts key and fetcher as...
Read more >
Shu on Twitter: "SWR 2.0 Beta 4: Resource preloading API to ...
Some good use cases for this API: 🔹 Preload top-level resources before the initial render; 🔹 Preload resources for the next page, when...
Read more >
Resource Preloaded With Link Preload Was Not Used
The real problem appears to be that tinvwl-webfont.woff2 preloads on every page, not just product and other pages where it is used. The...
Read more >
Link types: preload - HTML: HyperText Markup Language | MDN
The preload value of the element's rel attribute lets you declare fetch requests in the HTML's , specifying resources that your page will ......
Read more >
更新日志 – SWR
SWR first returns the data from cache (stale), then sends the fetch request (revalidate), ... SWR DevTools; Preload resource; Improved React 18 support....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found