DuCanhGH / next-pwa

PWA for Next.js, powered by Workbox.
https://ducanh-next-pwa.vercel.app
MIT License
620 stars 25 forks source link

Unable Cache API response #161

Closed rajashekhargithubb closed 2 months ago

rajashekhargithubb commented 2 months ago

Provide environment information

"@ducanh2912/next-pwa": "^10.2.8",
"next": "14.2.5",
"react": "18.2.0",
"@tanstack/react-query": "^4.29.12",

Link to reproduction - Issues with a link to complete (but minimal) reproduction code help us address them faster

No Link

To reproduce

Follow Installation steps with having Tanstack Query to fetch API's

Describe the bug

Unable to cache API's through running through Tanstack Query, Tried with fetch API still the issue persists.

module.exports = async (phase) => {
  if (phase === PHASE_DEVELOPMENT_SERVER || phase === PHASE_PRODUCTION_BUILD) {
    const withSerwist = require('@ducanh2912/next-pwa').default({
      // swSrc: 'service-workers/index.js',
      // swDest: 'public/sw.js',
      // cacheOnNavigation: true,
      // additionalPrecacheEntries: ['/setting/practice-details'],
      dest: 'public',
      aggressiveFrontEndNavCaching: true,
      // extendDefaultRuntimeCaching: true,
      cacheOnFrontEndNav: true,
      register: true,
      skipWaiting: true,
      workboxOptions: {
        mode: 'production',
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/fonts\.(?:googleapis|gstatic)\.com\/.*/i,
            handler: 'StaleWhileRevalidate',
            options: {
              cacheName: 'google-fonts',
              expiration: {
                maxEntries: 4,
                maxAgeSeconds: 1 * 24 * 60 * 60, // 1 days
              },
            },
          },
          {
            urlPattern: /\.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i,
            handler: 'StaleWhileRevalidate',
            options: {
              cacheName: 'static-font-assets',
              expiration: {
                maxEntries: 4,
                maxAgeSeconds: 7 * 24 * 60 * 60, // 7 days
              },
            },
          },
          {
            urlPattern: /\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'static-image-assets',
              expiration: {
                maxEntries: 64,
                maxAgeSeconds: 0.5 * 60 * 60, // 30m
              },
            },
          },
          {
            urlPattern: /\.(?:js)$/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'static-js-assets',
              expiration: {
                maxEntries: 32,
                maxAgeSeconds: 1 * 60 * 60, // 1 hours
              },
            },
          },
          {
            urlPattern: /\.(?:css|less)$/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'static-style-assets',
              expiration: {
                maxEntries: 32,
                maxAgeSeconds: 24 * 60 * 60, // 24 hours
              },
            },
          },
          {
            urlPattern: 'https://reqres.in/api/users?page=2',
            handler: 'NetworkFirst',
            method: 'GET',
            options: {
              cacheName: 'apis',
              expiration: {
                maxEntries: 16,
                maxAgeSeconds: 24 * 60 * 60, // 24 hours
              },
              networkTimeoutSeconds: 10, // fall back to cache if api does not response within 10 seconds
            },
          },
          {
            urlPattern: ({ url }) => {
              const isSameOrigin = self.origin === url.origin;
              if (!isSameOrigin) return false;

              const pathname = url.pathname;
              if (pathname.startsWith('/v1/auth/login')) return false;
              if (pathname.startsWith('/v1/')) return true;
              return false;
            },
            handler: 'NetworkFirst',
            method: 'GET',
            options: {
              cacheName: 'apis',
              expiration: {
                maxEntries: 16,
                maxAgeSeconds: 24 * 60 * 60, // 24 hours
              },
              networkTimeoutSeconds: 10, // fall back to cache if api does not response within 10 seconds
            },
          },
          {
            urlPattern: /.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'others',
              expiration: {
                maxEntries: 32,
                maxAgeSeconds: 24 * 60 * 60, // 24 hours
              },
              networkTimeoutSeconds: 10,
            },
          },
        ],
      },
    });
    return withSerwist(nextConfig);
  }

  return nextConfig;
};```

Tried the following ways but still no luck

  1. Tried using network always option in tanstack

  2. Tried in production mode

Q: Do self origin needs to be the same to cache API response? if yes whats the solution to cache other origin responses?

Expected behavior

Expecting to cache API responses flawlessly

Screenshots (if relevant)

image

Additional information (if relevant)

No response

rajashekhargithubb commented 2 months ago

@DuCanhGH Any insights??

DuCanhGH commented 2 months ago

For fuck's sake, have some patience, will ya? It was a bloody fucking state funeral over here.

Onto your question.

Workbox transforms your urlPattern string to new URL(urlPattern, location.href). So avoid using that. Consider a RegExp or a function. Now, if you use a RegExp, it has to match the entire requesting URL. So basically just go and use a function.

DuCanhGH commented 2 months ago

@rajashekhargithubb I was a bit mad last week with your prompting me to answer you. It was not the best time for us Vietnamese over here. I'd like to express my sorry for that. I do request that you have some patience the next time you open an issue though.

Now, let's take a proper look at your issue. Are you sure that the actual requested URL is exactly "https://reqres.in/api/users?page=2"? If that's the case, the route should match. If not, do recheck if Tanstack Query inserted anything to the URL. I don't use the library, so there's not much I can tell you about that.

You may also want to use a urlPattern function to check if the URL does actually match.

rajashekhargithubb commented 2 months ago

@DuCanhGH No Worries, I appreciate your response, I have fixed it using urlPattern with few logics.