47

I am following a simple PWA tutorial, but when I complete it I get the following console error,

Uncaught (in promise) TypeError: Failed to execute 'Cache' on 'addAll': Request failed

Here is my serviceworker file

const staticDevCoffee = "dev-coffee-site-v1"
const assets = [
  "/",
  "/test.html",
  "/csstest/style.css",
  "/jstest/app.js",
  "/coffee.png",
]

self.addEventListener("install", installEvent => {
  installEvent.waitUntil(
    caches.open(staticDevCoffee).then(cache => {
      cache.addAll(assets)
    })
  )
})

When I run lighthouse tests, I get this,

start_url does not respond with a 200 when offlineThe start_url did respond, but not via a service worker.

This is my first look at PWAs so I am a little stuck. I have tried several solutions I have found on SO, but none work.

Danny Jebb
  • 802
  • 1
  • 7
  • 16
  • 2
    Had this exact same error and glad it was already answered. Led me to a .icns file that wasn't being served properly (due to mime type not set) and which failed and caused ServcieWorker to fail. Thanks – raddevus Jun 22 '21 at 22:06
  • I also had this problem. No problem on a Windows pc and android phone, but on an Ipad the service worker was not working. The problem was an image i removed, but was still in the pre-cache list. – Tom Mar 14 '22 at 15:25

4 Answers4

71
  • For the first exception:-

    Uncaught (in promise) TypeError: Failed to execute 'Cache' on 'addAll': Request failed

You get this exception when any files which you have mentioned in your cache list return a 404 response. So make sure the all the resources are giving 200.

  • For the 2nd error:-

    start_url does not respond with a 200 when offlineThe start_url did respond.

In your case as files are not getting cached(due to first exception) you are getting this error and also make sure to cache root index file in your cache list.

Vimal Patel
  • 2,785
  • 2
  • 24
  • 38
3

Typos in the file list can be a common cause for failure (404). cache.addAll() fails the entire batch without providing any guidance on what exactly failed. Upon failure, the code below adds each file individually with cache.add() and logs which file failed.

Notes:

  • addAll() and add() are both promises, and async/await works well

  • Both return undefined on resolve()

  • addAll() error in try/catch is a very vague/unhelpful TypeError: Failed to execute 'addAll' on 'Cache': Request failed, which is why err is not output to console.error()

  • add() doesn't even provide an error, thus the far more useful loop item (filpath) in the console.warn()

    //code
    self.addEventListener('install', e => {
      e.waitUntil(caches.open(CACHE_NAME).then(async (cache) => {
        let ok,
        cats = [
          'a', 'folder', 'with',
          'lots', 'of', 'files',
          'for', 'the', 'same', 'extension'
        ],
        c = [
          '/css/video-js.css',
          '/img/base/favicon.ico',
          '/img/base/favicon.png',
          '/img/base/favicon.svg',
          ...cats.map(i => '/img/cat/' + i + '.jpg'),
          '/img/svg/404.svg',
          '/js/caman.full.min.js',
          '/js/jquery-3.6.0.min.js',
          '/js/video.min.js'
          ];
    
        console.log('ServiceWorker: Caching files:', c.length, c);
        try {
          ok = await cache.addAll(c);
        } catch (err) {
          console.error('sw: cache.addAll');
          for (let i of c) {
            try {
              ok = await cache.add(i);
            } catch (err) {
              console.warn('sw: cache.add',i);
            }
          }
        }
    
        return ok;
      }));
    
      console.log('ServiceWorker installed');
    });
    

With typos, the console output looks something like:

ServiceWorker installed

ServiceWorker: Caching files: 77

ServiceWorker registered: https://local.dev/

sw: cache.addAll

sw: cache.add /img/cat/booking.jpg

sw: cache.add /img/cat/prc.jpg

ServiceWorker activated

Fixed the typos (booking -> bookings, prc -> pr), unregistered the sw, reloaded the page. Log without typos:

ServiceWorker installed

ServiceWorker: Caching files: 77

ServiceWorker registered: https://local.dev/

ServiceWorker activated

Damm these fat fingers...

OXiGEN
  • 2,041
  • 25
  • 19
2

I had also issues with this: In my app I have tens of files in the assets[] array to load into cache, manually picked (i.e. it doesn't make sense to cache loading.gif since it is not needed after the loading). Then any forgotten change makes the cache empty and the cause of the error is hidden, as the accepted answer explains. After I repeatedly spent time searching what was missing, I lost my patience with "convenient" cache.addAll and switched back to cache.add, so instead of the useless TypeError I get reported the file which caused the failure:

...
const filesUpdate = cache => {
    const stack = [];
    assets.forEach(file => stack.push(
        cache.add(file).catch(_=>console.error(`can't load ${file} to cache`))
    ));
    return Promise.all(stack);
};

installEvent.waitUntil(caches.open(staticDevCoffee).then(filesUpdate));
...

I hope this saves somebody nerves with cache.addAll(), too.

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
0
self.addEventListener("install", (event) => {
    console.log("Service Worker : Installed!")

    event.waitUntil(
        
        (async() => {
            try {
                cache_obj = await caches.open(cache)
                cache_obj.addAll(caching_files)
            }
            catch{
                console.log("error occured while caching...")
            }
        })()
    )
} )

This code worked for me!

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
shilash M
  • 29
  • 2
  • This does not address the issue and instead simply ignores it. Your service worker will be installed but your cache will not work as expected with this code. The accepted answer is the correct way to handle this issue. If you are having issues that the solution above does not resolve, you should ask your own question. – Besworks May 27 '22 at 23:48
  • Worked fine for me https://github.com/shilu10/Service-Worker – shilash M May 28 '22 at 07:09