Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service Worker : How to handle a 302 redirect response

I installed a service worker on my application, it gets installed well, activated well, and the caching is ok too.

But when the caching is done when I click on a page that is a 302, it tells me:

The FetchEvent for "http://localhost:8000/form/" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".

I've been reading a lot on the subject, I've consulted the posts here : Service Worker breaking 301 redirects, and there https://github.com/w3c/ServiceWorker/issues/737 and there https://github.com/GoogleChromeLabs/sw-precache/issues/220

As I understand the default redirect mode when fetching is {redirect: "follow"}, but when I catch the redirect mode from my redirected page I can see it is {redirect: "manual"} So basically I would have to do something when it is "manual".

Thought I'm a bit confused and I'm struggling on how to implement this in my code.

Here's my code:

const STATIC_CACHE_NAME = 'exell-static-v28';
const DYNAMIC_CACHE_NAME = 'exell-dynamic-v4';

// INSTALLING THE SERVICE WORKER AND PRECACHING APPSHELL
self.addEventListener('install', function(event) {
  console.log('[Service Worker] Service Worker installed');
  event.waitUntil(
    caches.open(STATIC_CACHE_NAME) // Create a static cache
    .then(function(cache) {
      console.log('[Service Worker] Precaching App Shell');
      cache.addAll([   // Add static files to the cache
        '/',
        '/build/app.js',
        '/build/global.css',
        'login',
        'logout',
        'offline',
        'form/',
        'form/new/first_page',
        'form/new/second_page',
        'form/new/third_page',
        'form/new/fourth_page',
        'form/new/fifth_page',
        'form/new/sixth_page',
        'profile/',
        'build/fonts/BrandonGrotesque-Medium.a989c5b7.otf',
        'build/fonts/BrandonText-Regular.cc4e72bd.otf',
      ]);
    })
  );
});

// ACTIVATING THE SERVICE WORKER
self.addEventListener('activate', function(event) {
  console.log('[Service Worker] Service Worker activated');
  event.waitUntil(
    caches.keys()
    .then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== STATIC_CACHE_NAME && key !== DYNAMIC_CACHE_NAME) { // If old cache exists
          console.log('[Service Worker] Deleting old cache', key);
          return caches.delete(key);  // Delete it and replace by new one
        }
      }));
    })
  );
  return self.clients.claim();
});


// FETCHING
self.addEventListener('fetch', function(event) {

  // Do not waste time with files we don't want to cache
  if (event.request.url.match(/ajax.js/)) {
    return;
  }

  event.respondWith(
    caches.match(event.request) // Retrieve data from the cache
     .then(function(response) {
        if (response) {
          return response;  // If there is a response, return it
        } else {
          return fetch(event.request) // Otherwise fetch from network
            .then(function(res) {
              return caches.open(DYNAMIC_CACHE_NAME)
                .then(function(cache) {
                  cache.put(event.request.url, res.clone()); // Store the response in the dynamic cache
                  return res; // And return the response
                });
            })
            .catch(function() {  // If no network
              return caches.open(STATIC_CACHE_NAME) // Open the static cache
               .then(function(cache) {
                 cache.match('offline'); // Look for the offline default template and return it
               });
            });
         }
      })
    );
});
like image 491
Loann.M Avatar asked Apr 18 '18 07:04

Loann.M


People also ask

How do you fix a 302 redirect?

How to fix it? You should only use 302 redirects where the redirection is temporary and content will come back to the original URL soon. Check the reported URLs. Where the redirection is permanent, change the redirection to 301 (Moved Permanently).

How does a 302 redirect work?

A 302 redirect does not pass the “juice,” or keep your domain authority to its new location. It simply redirects the user to the new location for you so they don't view a broken link, a 404 not found page, or an error page.

How do you handle redirects?

Avoid chained redirects: one redirect should not forward to another redirect. Redirect to the preferred version of your website, using the right protocol (http or https), domain name (www or non-www) and path notation (with or without trailing slash). Use a 302 redirect for inactive campaigns.


1 Answers

Any 30x responses are expected to have a type property that resolves to "opaqueredirect", which you could check for, and react to appropriately. Maybe you would want to check this link: Response.type

opaqueredirect: The fetch request was made with redirect: "manual".
The Response's status is 0, headers are empty, body is null and trailer is empty.

Therefore to solve your issue, you should check for:

response.type === 'opaqueredirect'

instead of any checks relating to response.status, for example similar to
(the checks bellow will not work as response.status will be 0)

response.status === 301 || response.status === 302

Cheers, and happy coding!

like image 117
dankilev Avatar answered Sep 19 '22 08:09

dankilev