302 redirects do not work in a service worker built with Google Workbox












2















For having the "add tome homescreen" alert displayed, I want to integrate a service-worker and an offline capability of the application: When the user is offline, the app should simply display a special offline HTML file.



My service-worker looks like this:






importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.1.0/workbox-sw.js');

const CACHE_VERSION = 1;

workbox.core.setCacheNameDetails({
prefix: 'app',
suffix: 'v' + CACHE_VERSION
});

workbox.routing.registerRoute(
'/offline-page.html',
workbox.strategies.networkFirst({
networkTimeoutSeconds: 2,
cacheableResponse: { statuses: [0, 200] },
})
)

workbox.routing.registerRoute(
({ event }) => event.request.mode === 'navigate',
({ url }) =>
fetch(url.href, { credentials: 'include', redirect: 'follow', }).catch(() => caches.match('/offline-page.html'))
)





But as soon as my application returns a 302 redirect (e.g. after login oder logout), I get the following warning message in the console:




The FetchEvent for "https://app.com" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".




and Google Chrome diplays an error page (ERR_FAILED) saying that the website can't be reached.



Does anyone have an idea how to fix this?










share|improve this question





























    2















    For having the "add tome homescreen" alert displayed, I want to integrate a service-worker and an offline capability of the application: When the user is offline, the app should simply display a special offline HTML file.



    My service-worker looks like this:






    importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.1.0/workbox-sw.js');

    const CACHE_VERSION = 1;

    workbox.core.setCacheNameDetails({
    prefix: 'app',
    suffix: 'v' + CACHE_VERSION
    });

    workbox.routing.registerRoute(
    '/offline-page.html',
    workbox.strategies.networkFirst({
    networkTimeoutSeconds: 2,
    cacheableResponse: { statuses: [0, 200] },
    })
    )

    workbox.routing.registerRoute(
    ({ event }) => event.request.mode === 'navigate',
    ({ url }) =>
    fetch(url.href, { credentials: 'include', redirect: 'follow', }).catch(() => caches.match('/offline-page.html'))
    )





    But as soon as my application returns a 302 redirect (e.g. after login oder logout), I get the following warning message in the console:




    The FetchEvent for "https://app.com" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".




    and Google Chrome diplays an error page (ERR_FAILED) saying that the website can't be reached.



    Does anyone have an idea how to fix this?










    share|improve this question



























      2












      2








      2








      For having the "add tome homescreen" alert displayed, I want to integrate a service-worker and an offline capability of the application: When the user is offline, the app should simply display a special offline HTML file.



      My service-worker looks like this:






      importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.1.0/workbox-sw.js');

      const CACHE_VERSION = 1;

      workbox.core.setCacheNameDetails({
      prefix: 'app',
      suffix: 'v' + CACHE_VERSION
      });

      workbox.routing.registerRoute(
      '/offline-page.html',
      workbox.strategies.networkFirst({
      networkTimeoutSeconds: 2,
      cacheableResponse: { statuses: [0, 200] },
      })
      )

      workbox.routing.registerRoute(
      ({ event }) => event.request.mode === 'navigate',
      ({ url }) =>
      fetch(url.href, { credentials: 'include', redirect: 'follow', }).catch(() => caches.match('/offline-page.html'))
      )





      But as soon as my application returns a 302 redirect (e.g. after login oder logout), I get the following warning message in the console:




      The FetchEvent for "https://app.com" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".




      and Google Chrome diplays an error page (ERR_FAILED) saying that the website can't be reached.



      Does anyone have an idea how to fix this?










      share|improve this question
















      For having the "add tome homescreen" alert displayed, I want to integrate a service-worker and an offline capability of the application: When the user is offline, the app should simply display a special offline HTML file.



      My service-worker looks like this:






      importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.1.0/workbox-sw.js');

      const CACHE_VERSION = 1;

      workbox.core.setCacheNameDetails({
      prefix: 'app',
      suffix: 'v' + CACHE_VERSION
      });

      workbox.routing.registerRoute(
      '/offline-page.html',
      workbox.strategies.networkFirst({
      networkTimeoutSeconds: 2,
      cacheableResponse: { statuses: [0, 200] },
      })
      )

      workbox.routing.registerRoute(
      ({ event }) => event.request.mode === 'navigate',
      ({ url }) =>
      fetch(url.href, { credentials: 'include', redirect: 'follow', }).catch(() => caches.match('/offline-page.html'))
      )





      But as soon as my application returns a 302 redirect (e.g. after login oder logout), I get the following warning message in the console:




      The FetchEvent for "https://app.com" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".




      and Google Chrome diplays an error page (ERR_FAILED) saying that the website can't be reached.



      Does anyone have an idea how to fix this?






      importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.1.0/workbox-sw.js');

      const CACHE_VERSION = 1;

      workbox.core.setCacheNameDetails({
      prefix: 'app',
      suffix: 'v' + CACHE_VERSION
      });

      workbox.routing.registerRoute(
      '/offline-page.html',
      workbox.strategies.networkFirst({
      networkTimeoutSeconds: 2,
      cacheableResponse: { statuses: [0, 200] },
      })
      )

      workbox.routing.registerRoute(
      ({ event }) => event.request.mode === 'navigate',
      ({ url }) =>
      fetch(url.href, { credentials: 'include', redirect: 'follow', }).catch(() => caches.match('/offline-page.html'))
      )





      importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.1.0/workbox-sw.js');

      const CACHE_VERSION = 1;

      workbox.core.setCacheNameDetails({
      prefix: 'app',
      suffix: 'v' + CACHE_VERSION
      });

      workbox.routing.registerRoute(
      '/offline-page.html',
      workbox.strategies.networkFirst({
      networkTimeoutSeconds: 2,
      cacheableResponse: { statuses: [0, 200] },
      })
      )

      workbox.routing.registerRoute(
      ({ event }) => event.request.mode === 'navigate',
      ({ url }) =>
      fetch(url.href, { credentials: 'include', redirect: 'follow', }).catch(() => caches.match('/offline-page.html'))
      )






      javascript service-worker progressive-web-apps workbox






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 28 '18 at 13:26







      Tineler

















      asked Apr 28 '18 at 7:38









      TinelerTineler

      9611




      9611
























          2 Answers
          2






          active

          oldest

          votes


















          2














          You can adapt the "Provide a fallback response to a route" recipe in the docs to accommodate your particular restrictions.



          There are a couple of different options for accomplishing this, but the cleanest would be to create your own network-only strategy (to mimic the fetch() that you're using in your example), chain .catch() to the end of it, and then use that as the handler when constructing a NavigationRoute.



          That will give you a Route that you could then pass to workbox.routing.registerRoute().



          // You're responsible for either precaching or
          // explicitly adding OFFLINE_HTML to one of the caches.
          const OFFLINE_HTML = '/offline-page.html';
          const networkOnly = workbox.strategies.networkOnly();
          const networkOnlyWithFallback = networkOnly().catch(() => caches.match(OFFLINE_HTML));
          const route = new workbox.routing.NavigationRoute(networkOnlyWithFallback);
          workbox.routing.registerRoute(route);





          share|improve this answer


























          • If I use your code, I get the following error: Uncaught TypeError: networkOnly.catch is not a function. Also right now I'm doing exactly what you posted here: GitHub Issue. It's just that 302 redirects are not processed correctly by my service-worker...

            – Tineler
            May 4 '18 at 6:30













          • Sorry, I left out parenthesis after networkOnly()

            – Jeff Posnick
            May 6 '18 at 18:29



















          0














          This seems to do the trick:



          const FALLBACK_URL = '/';

          const networkOnly = workbox.strategies.networkOnly();

          const route = new workbox.routing.NavigationRoute(({event}) => {
          return networkOnly.handle({event})
          .catch(() => caches.match(FALLBACK_URL));
          });

          workbox.routing.registerRoute(route);





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50074107%2f302-redirects-do-not-work-in-a-service-worker-built-with-google-workbox%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            You can adapt the "Provide a fallback response to a route" recipe in the docs to accommodate your particular restrictions.



            There are a couple of different options for accomplishing this, but the cleanest would be to create your own network-only strategy (to mimic the fetch() that you're using in your example), chain .catch() to the end of it, and then use that as the handler when constructing a NavigationRoute.



            That will give you a Route that you could then pass to workbox.routing.registerRoute().



            // You're responsible for either precaching or
            // explicitly adding OFFLINE_HTML to one of the caches.
            const OFFLINE_HTML = '/offline-page.html';
            const networkOnly = workbox.strategies.networkOnly();
            const networkOnlyWithFallback = networkOnly().catch(() => caches.match(OFFLINE_HTML));
            const route = new workbox.routing.NavigationRoute(networkOnlyWithFallback);
            workbox.routing.registerRoute(route);





            share|improve this answer


























            • If I use your code, I get the following error: Uncaught TypeError: networkOnly.catch is not a function. Also right now I'm doing exactly what you posted here: GitHub Issue. It's just that 302 redirects are not processed correctly by my service-worker...

              – Tineler
              May 4 '18 at 6:30













            • Sorry, I left out parenthesis after networkOnly()

              – Jeff Posnick
              May 6 '18 at 18:29
















            2














            You can adapt the "Provide a fallback response to a route" recipe in the docs to accommodate your particular restrictions.



            There are a couple of different options for accomplishing this, but the cleanest would be to create your own network-only strategy (to mimic the fetch() that you're using in your example), chain .catch() to the end of it, and then use that as the handler when constructing a NavigationRoute.



            That will give you a Route that you could then pass to workbox.routing.registerRoute().



            // You're responsible for either precaching or
            // explicitly adding OFFLINE_HTML to one of the caches.
            const OFFLINE_HTML = '/offline-page.html';
            const networkOnly = workbox.strategies.networkOnly();
            const networkOnlyWithFallback = networkOnly().catch(() => caches.match(OFFLINE_HTML));
            const route = new workbox.routing.NavigationRoute(networkOnlyWithFallback);
            workbox.routing.registerRoute(route);





            share|improve this answer


























            • If I use your code, I get the following error: Uncaught TypeError: networkOnly.catch is not a function. Also right now I'm doing exactly what you posted here: GitHub Issue. It's just that 302 redirects are not processed correctly by my service-worker...

              – Tineler
              May 4 '18 at 6:30













            • Sorry, I left out parenthesis after networkOnly()

              – Jeff Posnick
              May 6 '18 at 18:29














            2












            2








            2







            You can adapt the "Provide a fallback response to a route" recipe in the docs to accommodate your particular restrictions.



            There are a couple of different options for accomplishing this, but the cleanest would be to create your own network-only strategy (to mimic the fetch() that you're using in your example), chain .catch() to the end of it, and then use that as the handler when constructing a NavigationRoute.



            That will give you a Route that you could then pass to workbox.routing.registerRoute().



            // You're responsible for either precaching or
            // explicitly adding OFFLINE_HTML to one of the caches.
            const OFFLINE_HTML = '/offline-page.html';
            const networkOnly = workbox.strategies.networkOnly();
            const networkOnlyWithFallback = networkOnly().catch(() => caches.match(OFFLINE_HTML));
            const route = new workbox.routing.NavigationRoute(networkOnlyWithFallback);
            workbox.routing.registerRoute(route);





            share|improve this answer















            You can adapt the "Provide a fallback response to a route" recipe in the docs to accommodate your particular restrictions.



            There are a couple of different options for accomplishing this, but the cleanest would be to create your own network-only strategy (to mimic the fetch() that you're using in your example), chain .catch() to the end of it, and then use that as the handler when constructing a NavigationRoute.



            That will give you a Route that you could then pass to workbox.routing.registerRoute().



            // You're responsible for either precaching or
            // explicitly adding OFFLINE_HTML to one of the caches.
            const OFFLINE_HTML = '/offline-page.html';
            const networkOnly = workbox.strategies.networkOnly();
            const networkOnlyWithFallback = networkOnly().catch(() => caches.match(OFFLINE_HTML));
            const route = new workbox.routing.NavigationRoute(networkOnlyWithFallback);
            workbox.routing.registerRoute(route);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 6 '18 at 18:28

























            answered Apr 30 '18 at 19:59









            Jeff PosnickJeff Posnick

            29.1k46092




            29.1k46092













            • If I use your code, I get the following error: Uncaught TypeError: networkOnly.catch is not a function. Also right now I'm doing exactly what you posted here: GitHub Issue. It's just that 302 redirects are not processed correctly by my service-worker...

              – Tineler
              May 4 '18 at 6:30













            • Sorry, I left out parenthesis after networkOnly()

              – Jeff Posnick
              May 6 '18 at 18:29



















            • If I use your code, I get the following error: Uncaught TypeError: networkOnly.catch is not a function. Also right now I'm doing exactly what you posted here: GitHub Issue. It's just that 302 redirects are not processed correctly by my service-worker...

              – Tineler
              May 4 '18 at 6:30













            • Sorry, I left out parenthesis after networkOnly()

              – Jeff Posnick
              May 6 '18 at 18:29

















            If I use your code, I get the following error: Uncaught TypeError: networkOnly.catch is not a function. Also right now I'm doing exactly what you posted here: GitHub Issue. It's just that 302 redirects are not processed correctly by my service-worker...

            – Tineler
            May 4 '18 at 6:30







            If I use your code, I get the following error: Uncaught TypeError: networkOnly.catch is not a function. Also right now I'm doing exactly what you posted here: GitHub Issue. It's just that 302 redirects are not processed correctly by my service-worker...

            – Tineler
            May 4 '18 at 6:30















            Sorry, I left out parenthesis after networkOnly()

            – Jeff Posnick
            May 6 '18 at 18:29





            Sorry, I left out parenthesis after networkOnly()

            – Jeff Posnick
            May 6 '18 at 18:29













            0














            This seems to do the trick:



            const FALLBACK_URL = '/';

            const networkOnly = workbox.strategies.networkOnly();

            const route = new workbox.routing.NavigationRoute(({event}) => {
            return networkOnly.handle({event})
            .catch(() => caches.match(FALLBACK_URL));
            });

            workbox.routing.registerRoute(route);





            share|improve this answer




























              0














              This seems to do the trick:



              const FALLBACK_URL = '/';

              const networkOnly = workbox.strategies.networkOnly();

              const route = new workbox.routing.NavigationRoute(({event}) => {
              return networkOnly.handle({event})
              .catch(() => caches.match(FALLBACK_URL));
              });

              workbox.routing.registerRoute(route);





              share|improve this answer


























                0












                0








                0







                This seems to do the trick:



                const FALLBACK_URL = '/';

                const networkOnly = workbox.strategies.networkOnly();

                const route = new workbox.routing.NavigationRoute(({event}) => {
                return networkOnly.handle({event})
                .catch(() => caches.match(FALLBACK_URL));
                });

                workbox.routing.registerRoute(route);





                share|improve this answer













                This seems to do the trick:



                const FALLBACK_URL = '/';

                const networkOnly = workbox.strategies.networkOnly();

                const route = new workbox.routing.NavigationRoute(({event}) => {
                return networkOnly.handle({event})
                .catch(() => caches.match(FALLBACK_URL));
                });

                workbox.routing.registerRoute(route);






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 '18 at 15:46









                Patrik BeckPatrik Beck

                1,1131915




                1,1131915






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50074107%2f302-redirects-do-not-work-in-a-service-worker-built-with-google-workbox%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Sphinx de Gizeh

                    Dijon

                    Guerrita