Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Service worker fetch event passing in wrong type

I add a fetch event listener like this

self.addEventListener( 'fetch', fetch )

and here is my fetch function

const fetch = e => {
    console.log({e})
    if ( !e.request.url.startsWith( self.location.origin ) || e.request.method !== 'GET' ) return

    const save = async res => {
        const cache = await caches.open( dynamic )
        cache.put( e.request, res )
    }

    const process = async cached => {
        if ( cached ) return cached
        const res = await fetch( e.request.clone() )
        if ( res ) await save( res.clone() )
        return res
    }

    e.respondWith( caches.match( e.request ).then( process ))
}

When I look at the event thats being passed in, I expect a fetch event but this is what I see

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

console log

Its printing a request object after the correct Fetch event. When i try to access the url, it will of course throw an error as it will effectively be doing request.request.url

>Solution :

In your process method, you’re calling the fetch function using a cloned Request, which is probably the Request you see in your console.

const res = await fetch( e.request.clone() )

This issue is because your custom method is called fetch, but in this case you probably want to use the native fetch method. Perhaps you should consider renaming your custom method to prevent conflicts like this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading