Giter VIP home page Giter VIP logo

next-pwa's Introduction

Zero Config PWA Plugin for Next.js

This plugin is powered by workbox and other good stuff.

size dependencies downloads license

👋 Share your awesome PWA project 👉 here

Features

  • 0️⃣ Zero config for registering and generating service worker
  • ✨ Optimized precache and runtime cache
  • 💯 Maximize lighthouse score
  • 🎈 Easy to understand examples
  • 📴 Completely offline support with fallbacks example 🆕
  • 📦 Use workbox and workbox-window v6
  • 🍪 Work with cookies out of the box
  • 🔉 Default range requests for audios and videos
  • ☕ No custom server needed for Next.js 9+ example
  • 🔧 Handle PWA lifecycle events opt-in example
  • 📐 Custom worker to run extra code with code splitting and typescript support example
  • 📜 Public environment variables available in custom worker as usual
  • 🐞 Debug service worker with confidence in development mode without caching
  • 🌏 Internationalization (a.k.a I18N) with next-i18next example
  • 🛠 Configurable by the same workbox configuration options for GenerateSW and InjectManifest
  • 🚀 Spin up a GitPod and try out examples in rocket speed
  • ⚡ Support blitz.js (simply add to blitz.config.js)
  • 🔩 (Experimental) precaching .module.js when next.config.js has experimental.modern set to true

NOTE 1 - next-pwa version 2.0.0+ should only work with next.js 9.1+, and static files should only be served through public directory. This will make things simpler.

NOTE 2 - If you encounter error TypeError: Cannot read property **'javascript' of undefined** during build, please consider upgrade to webpack5 in next.config.js.


Open in Gitpod

Install

If you are new to next.js or react.js at all, you may want to first checkout learn next.js or next.js document. Then start from a simple example or progressive-web-app example in next.js repository.

yarn add next-pwa

Basic Usage

Step 1: withPWA

Update or create next.config.js with

const withPWA = require('next-pwa')({
  dest: 'public'
})

module.exports = withPWA({
  // next.js config
})

After running next build, this will generate two files in your public: workbox-*.js and sw.js, which will automatically be served statically.

If you are using Next.js version 9 or newer, then skip the options below and move on to Step 2.

If you are using Next.js older than version 9, you'll need to pick an option below before continuing to Step 2.

Option 1: Host Static Files

Copy files to your static file hosting server, so that they are accessible from the following paths: https://yourdomain.com/sw.js and https://yourdomain.com/workbox-*.js.

One example is using Firebase hosting service to host those files statically. You can automate the copy step using scripts in your deployment workflow.

For security reasons, you must host these files directly from your domain. If the content is delivered using a redirect, the browser will refuse to run the service worker.

Option 2: Use Custom Server

When an HTTP request is received, test if those files are requested, then return those static files.

Example server.js

const { createServer } = require('http')
const { join } = require('path')
const { parse } = require('url')
const next = require('next')

const app = next({ dev: process.env.NODE_ENV !== 'production' })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = parse(req.url, true)
    const { pathname } = parsedUrl

    if (pathname === '/sw.js' || /^\/(workbox|worker|fallback)-\w+\.js$/.test(pathname)) {
      const filePath = join(__dirname, '.next', pathname)
      app.serveStatic(req, res, filePath)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(3000, () => {
    console.log(`> Ready on http://localhost:${3000}`)
  })
})

The following setup has nothing to do with next-pwa plugin, and you probably have already set them up. If not, go ahead and set them up.

Step 2: Add Manifest File (Example)

Create a manifest.json file in your public folder:

{
  "name": "PWA App",
  "short_name": "App",
  "icons": [
    {
      "src": "/icons/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "/icons/android-chrome-384x384.png",
      "sizes": "384x384",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "theme_color": "#FFFFFF",
  "background_color": "#FFFFFF",
  "start_url": "/",
  "display": "standalone",
  "orientation": "portrait"
}

Step 3: Add Head Meta (Example)

Add the following into _document.jsx or _app.tsx, in <Head>:

<meta name="application-name" content="PWA App" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<meta name="apple-mobile-web-app-title" content="PWA App" />
<meta name="description" content="Best PWA App in the world" />
<meta name="format-detection" content="telephone=no" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="msapplication-config" content="/icons/browserconfig.xml" />
<meta name="msapplication-TileColor" content="#2B5797" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="theme-color" content="#000000" />

<link rel="apple-touch-icon" href="/icons/touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="152x152" href="/icons/touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/icons/touch-icon-iphone-retina.png" />
<link rel="apple-touch-icon" sizes="167x167" href="/icons/touch-icon-ipad-retina.png" />

<link rel="icon" type="image/png" sizes="32x32" href="/icons/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/icons/favicon-16x16.png" />
<link rel="manifest" href="/manifest.json" />
<link rel="mask-icon" href="/icons/safari-pinned-tab.svg" color="#5bbad5" />
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" />

<meta name="twitter:card" content="summary" />
<meta name="twitter:url" content="https://yourdomain.com" />
<meta name="twitter:title" content="PWA App" />
<meta name="twitter:description" content="Best PWA App in the world" />
<meta name="twitter:image" content="https://yourdomain.com/icons/android-chrome-192x192.png" />
<meta name="twitter:creator" content="@DavidWShadow" />
<meta property="og:type" content="website" />
<meta property="og:title" content="PWA App" />
<meta property="og:description" content="Best PWA App in the world" />
<meta property="og:site_name" content="PWA App" />
<meta property="og:url" content="https://yourdomain.com" />
<meta property="og:image" content="https://yourdomain.com/icons/apple-touch-icon.png" />

<!-- apple splash screen images -->
<!--
<link rel='apple-touch-startup-image' href='/images/apple_splash_2048.png' sizes='2048x2732' />
<link rel='apple-touch-startup-image' href='/images/apple_splash_1668.png' sizes='1668x2224' />
<link rel='apple-touch-startup-image' href='/images/apple_splash_1536.png' sizes='1536x2048' />
<link rel='apple-touch-startup-image' href='/images/apple_splash_1125.png' sizes='1125x2436' />
<link rel='apple-touch-startup-image' href='/images/apple_splash_1242.png' sizes='1242x2208' />
<link rel='apple-touch-startup-image' href='/images/apple_splash_750.png' sizes='750x1334' />
<link rel='apple-touch-startup-image' href='/images/apple_splash_640.png' sizes='640x1136' />
-->

Tip: Put the viewport head meta tag into _app.js rather than in _document.js if you need it.

<meta
  name='viewport'
  content='minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no, user-scalable=no, viewport-fit=cover'
/>

Offline Fallbacks

Offline fallbacks are useful when the fetch failed from both cache and network, a precached resource is served instead of present an error from browser.

To get started simply add a /_offline page such as pages/_offline.js or pages/_offline.jsx or pages/_offline.ts or pages/_offline.tsx. Then you are all set! When the user is offline, all pages which are not cached will fallback to '/_offline'.

Use this example to see it in action

next-pwa helps you precache those resources on the first load, then inject a fallback handler to handlerDidError plugin to all runtimeCaching configs, so that precached resources are served when fetch failed.

You can also setup precacheFallback.fallbackURL in your runtimeCaching config entry to implement similar functionality. The difference is that above method is based on the resource type, this method is based matched url pattern. If this config is set in the runtimeCaching config entry, resource type based fallback will be disabled automatically for this particular url pattern to avoid conflict.

Configuration

There are options you can use to customize the behavior of this plugin by adding pwa object in the next config in next.config.js:

const withPWA = require('next-pwa')({
  dest: 'public'
  // disable: process.env.NODE_ENV === 'development',
  // register: true,
  // scope: '/app',
  // sw: 'service-worker.js',
  //...
})

module.exports = withPWA({
  // next.js config
})

Available Options

  • disable: boolean - whether to disable pwa feature as a whole
    • default: false
    • set disable: false, so that it will generate service worker in both dev and prod
    • set disable: true to completely disable PWA
    • if you don't need to debug service worker in dev, you can set disable: process.env.NODE_ENV === 'development'
  • register: boolean - whether to let this plugin register service worker for you
    • default to true
    • set to false when you want to handle register service worker yourself, this could be done in componentDidMount of your root app. you can consider the register.js as an example.
  • scope: string - url scope for pwa
    • default: basePath in next.config.js or /
    • set to /app so that path under /app will be PWA while others are not
  • sw: string - service worker script file name
    • default: /sw.js
    • set to another file name if you want to customize the output file name
  • runtimeCaching - caching strategies (array or callback function)
    • default: see the Runtime Caching section for the default configuration
    • accepts an array of cache entry objects, please follow the structure here
    • Note: the order of the array matters. The first rule that matches is effective. Therefore, please ALWAYS put rules with larger scope behind the rules with a smaller and specific scope.
  • publicExcludes - an array of glob pattern strings to exclude files in the public folder from being precached.
    • default: ['!noprecache/**/*'] - this means that the default behavior will precache all the files inside your public folder but files inside /public/noprecache folder. You can simply put files inside that folder to not precache them without config this.
    • example: ['!img/super-large-image.jpg', '!fonts/not-used-fonts.otf']
  • buildExcludes - an array of extra pattern or function to exclude files from being precached in .next/static (or your custom build) folder
    • default: []
    • example: [/chunks\/images\/.*$/] - Don't precache files under .next/static/chunks/images (Highly recommend this to work with next-optimized-images plugin)
    • doc: Array of (string, RegExp, or function()). One or more specifiers used to exclude assets from the precache manifest. This is interpreted following the same rules as Webpack's standard exclude option.
  • cacheStartUrl - whether to cache start url
  • dynamicStartUrl - if your start url returns different HTML document under different state (such as logged in vs. not logged in), this should be set to true.
    • default: true
    • effective when cacheStartUrl set to true
    • recommend: set to false if your start url always returns same HTML document, then start url will be precached, this will help to speed up first load.
  • dynamicStartUrlRedirect - if your start url redirect to another route such as /login, it's recommended to setup this redirected url for the best user experience.
    • default: undefined
    • effective when dynamicStartUrlRedirect set to true
  • fallbacks - config precached routes to fallback when both cache and network not available to serve resources.
    • if you just need a offline fallback page, simply create a /_offline page such as pages/_offline.js and you are all set, no configuration necessary
    • default: object
      • fallbacks.document - fallback route for document (page), default to /_offline if you created that page
      • fallbacks.image - fallback route for image, default to none
      • fallbacks.audio - fallback route for audio, default to none
      • fallbacks.video - fallback route for video, default to none
      • fallbacks.font - fallback route for font, default to none
  • cacheOnFrontEndNav - enable additional route cache when navigate between pages with next/link on front end. Checkout this example for some context about why this is implemented.
    • default: false
    • note: this improve user experience on special use cases but it also adds some overhead because additional network call, I suggest you consider this as a trade off.
  • subdomainPrefix: string - url prefix to allow hosting static files on a subdomain
    • default: "" - i.e. default with no prefix
    • example: /subdomain if the app is hosted on example.com/subdomain
    • deprecated, use basePath instead
  • reloadOnOnline - changes the behaviour of the app when the device detects that it has gone back "online" and has a network connection. Indicate if the app should call location.reload() to refresh the app.
    • default: true
  • customWorkerDir - customize the directory where next-pwa looks for a custom worker implementation to add to the service worker generated by workbox. For more information, check out the custom worker example.
    • default: worker

Other Options

next-pwa uses workbox-webpack-plugin, other options which could also be put in pwa object can be found ON THE DOCUMENTATION for GenerateSW and InjectManifest. If you specify swSrc, InjectManifest plugin will be used, otherwise GenerateSW will be used to generate service worker.

Runtime Caching

next-pwa uses a default runtime cache.js

There is a great chance you may want to customize your own runtime caching rules. Please feel free to copy the default cache.js file and customize the rules as you like. Don't forget to inject the configurations into your pwa config in next.config.js.

Here is the document on how to write runtime caching configurations, including background sync and broadcast update features and more!

Tips

  1. Common UX pattern to ask user to reload when new service worker is installed
  2. Use a convention like {command: 'doSomething', message: ''} object when postMessage to service worker. So that on the listener, it could do multiple different tasks using if...else....
  3. When you are debugging service worker, constantly clean application cache to reduce some flaky errors.
  4. If you are redirecting the user to another route, please note workbox by default only cache response with 200 HTTP status, if you really want to cache redirected page for the route, you can specify it in runtimeCaching such as options.cacheableResponse.statuses=[200,302].
  5. When debugging issues, you may want to format your generated sw.js file to figure out what's really going on.
  6. Force next-pwa to generate worker box production build by specify the option mode: 'production' in your pwa section of next.config.js. Though next-pwa automatically generate the worker box development build during development (by running next) and worker box production build during production (by running next build and next start). You may still want to force it to production build even during development of your web app for following reason:
    1. Reduce logging noise due to production build doesn't include logging.
    2. Improve performance a bit due to production build is optimized and minified.
  7. If you just want to disable worker box logging while keeping development build during development, simply put self.__WB_DISABLE_DEV_LOGS = true in your worker/index.js (create one if you don't have one).
  8. It is common developers have to use userAgent string to determine if users are using Safari/iOS/MacOS or some other platform, ua-parser-js library is a good friend for that purpose.

Reference

  1. Google Workbox
  2. ServiceWorker, MessageChannel, & postMessage by Nicolás Bevacqua
  3. The Service Worker Lifecycle
  4. 6 Tips to make your iOS PWA feel like a native app
  5. Make Your PWA Available on Google Play Store

Fun PWA Projects

  1. Experience SAMSUNG on an iPhone - must open on an iPhone to start
  2. App Scope - like an app store for PWA
  3. PWA Directory
  4. PWA Builder - Alternative way to build awesome PWA

License

MIT

next-pwa's People

Contributors

bram-zijp avatar clfhhc avatar crubier avatar cubxity avatar dependabot[bot] avatar dtinth avatar felixmosh avatar g-farrow avatar ghpranav avatar hamen avatar ihavecoke avatar jerrygreen avatar jonahsnider avatar juanod avatar karlhorky avatar lucasmallmann avatar lukasdotcom avatar max-programming avatar numb86 avatar pascuflow avatar pytal avatar redian avatar shadowwalker avatar shrashiti avatar styfle avatar tevinthuku avatar thrsouza avatar timowilhelm avatar wmcb91 avatar zebapy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

next-pwa's Issues

TODO

  • example with next-i18next
  • enable on dev - prevent rebuild SW on hot reload
  • new option of glob pattern to include/exclude files in public folder - currently it pre-cache everything in public/
  • conventional workers folder to write custom service worker code with webpack bundling

Custom Worker to prevent default installation

Hi there!

I'm trying to block the default installation prompt "Add to Homescreen" as I want to provide a custom install experience!

As stated in this article: https://web.dev/customize-install/ I had to listen to the 'beforeinstallprompt' event, and work from there.

I followed the examples in this repo to use a custom worker, by creating a worker/index.js in the root of my project. All I wrote in that index is to prevent the default installation prompt, like this:

self.addEventListener('beforeinstallprompt', (e) => {
  // Prevent the mini-infobar from appearing on mobile
  e.preventDefault();
});

This worker is being loaded to the public folder, as expected...but the "Add to Homescreen" is still appearing :/ Any idea on how to acomplish this, please?

Error: Cannot find module 'fs-extra'

fs-extra is used by next-pwa but not actually in the dependencies. This makes the library totally unusable for anyone using

  • A package manager that uses PnP
  • Yarn 2
  • Anyone who isn't coincidentally installing a package that properly depends on fs-extra
$ next build

> Build error occurred
Error: Cannot find module 'fs-extra'
Require stack:
- /usr/src/project/node_modules/next-pwa/index.js
- /usr/src/project/next.config.js
- /usr/src/project/node_modules/next/dist/next-server/server/config.js
- /usr/src/project/node_modules/next/dist/build/index.js
- /usr/src/project/node_modules/next/dist/cli/next-build.js
- /usr/src/project/node_modules/next/dist/bin/next
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
    at Function.Module._load (internal/modules/cjs/loader.js:842:27)
    at Module.require (internal/modules/cjs/loader.js:1026:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/usr/src/project/node_modules/next-pwa/index.js:4:12)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Module.require (internal/modules/cjs/loader.js:1026:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/usr/src/project/node_modules/next-pwa/index.js',
    '/usr/src/project/next.config.js',
    '/usr/src/project/node_modules/next/dist/next-server/server/config.js',
    '/usr/src/project/node_modules/next/dist/build/index.js',
    '/usr/src/project/node_modules/next/dist/cli/next-build.js',
    '/usr/src/project/node_modules/next/dist/bin/next'
  ]
}

`additionalManifestEntries` gets overriden when provided.

I am not sure if this is the expected behavior but providing additionalManifestEntries option to pwa config causes the if block at

if (!Array.isArray(manifestEntries)) {
not to run, which ends up dropping all the public folder content. I am using that in order to add a static HTML as additionalManifestEntries: [{ url: "offline", revision: nanoid() }],. I could get over this problem by simply copy/pasting the if block, but I think it might make more sense if the library worked in an additive fashion for additionalManifestEntries option. Especially given there is already a publicExcludes option. @shadowwalker wdyt? Happy to work on a PR if you think this makes sense.

How to avoid caching API requests at all?

What config should I set to avoid caching XHR api requests
I managed to doing this, so it is cached for 1 second

runtimeCaching: [
      {
        urlPattern: /\/api\//g,
        handler: 'NetworkFirst',
        options: {
          cacheName: 'api',
          expiration: {
            maxEntries: 1,
            maxAgeSeconds: 1 
          }
        }
      }
    ],

[question] additionalManifestEntries revision ID

in next.config.js custom configuration is there any way to get revision if we have provided additionalManifestEntries for precaching routes? or we can just randomly generate and provide it?

because providing null actilly caches it sorta permanantly and doesn't reflect changes after hard reload

Here's a sample behaviour on precache route with null as revision build id reverts back even after empty cache and hard reload
Peek 2020-05-05 17-17

Cannot register service worker with minimal configuration on Netlify

Error message in the console shows....

SW registration failed: TypeError: Failed to register a ServiceWorker for scope ('https://stupefied-franklin-ead670.netlify.com/') with script ('https://stupefied-franklin-ead670.netlify.com/service-worker.js'): A bad HTTP response code (404) was received when fetching the script.

The build files generate and SW.js, rather than a service-worker.js.

Could there be some additional configuration I am missing?

Broken in dev mode

When running in dev mode:

image

It eventually gets stuck requesting resources.

sw.js file is not generate when building

I dont have any sw.js file inside public folder when building. This is how I am using next-pwa

const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");
const withPWA = require("next-pwa");

module.exports = withPlugins(
    [optimizedImages],
    [
      withPWA({
        pwa: {
          dest: "public",
        },
      }),
    ]
);

after refresh not show cached page

hi. I am using next-pwa and every thing is ok. but when user is offline , user can navigate between cjacjed page but after refresh in page no internet error show

Always return an app-shell when user if offline.

One of the main benefits of a PWA is that all URLs respond with a 200 and a working app shell.

In an ideal scenario a nextjs PWA would respond with an app-shell which could be created by a user by accessing something like /pages/_app-shell.js (which can have 'blank' default like _404 is)

When a user accesses a random URL it will always return the contents of _app-shell.js. The client app will navigate to the page if the user is online, if the user is offline offline it wont and it will show a 'you are offline message'.

Question re: `navigateFallback`

First of all, thank you for this library @shadowwalker. I am trying to apply the "app shell" model using next-pwa. I created an /offline route that gets statically compiled into .next/static/{BUILD_ID}/pages/offline.html. I am trying to use that file as my navigateFallback. Simply doing navigateFallback: "/offline" is not working, as that route is not pre-cached. After spending some time I wanted to ask whether I am missing something. Right now, I am considering having a custom build step that would cp that file into public/ so that navigateFallback: "/offline.html" could be used. I was wondering if anyone using next-pwa had a more elegant solution. Thanks!

Error while building the next-9 example

Issue

Error while trying to install and build the example for installing next-pwa on Next v9+ .

Expected Output

Successful Build with PWA ready Next App

Steps

> [email protected] build /<dir>/next-9
> next build

> [PWA] compile client (static)
> [PWA] auto register service worker with: /<dir>t/next-9/node_modules/next-pwa/register.js
> [PWA] service worker: /<dir>/next-9/public/sw.js
> [PWA]   url: /sw.js
> [PWA]   scope: /
> [PWA] precache manifest: /<dir>/next-9/public/precache.ykumYKjvIaxEuyzC-fB1q.[manifestHash].js
> [PWA] compile server
Creating an optimized production build

Failed to compile.

Please check your GenerateSW plugin configuration:
"importsDirectory" is not a supported parameter.. "globDirectory" is not a supported parameter.. "globPatterns" is not a supported parameter.. "precacheManifestFilename" is not a supported parameter.

> Build error occurred
Error: > Build failed because of webpack errors
    at build (/<dir>/next-9/node_modules/next/dist/build/index.js:10:900)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /<dir>/.npm/_logs/2020-02-08T13_39_59_180Z-debug.log

Wrong path in precaching from workbox

When I visit my exported site (by locally serving the /out directory) I get this error:

workbox-07643d7a.js:1 Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"http://localhost:3000/public/pwa/android-chrome-144x144.png","status":404}]
    at D (http://localhost:3000/workbox-07643d7a.js:1:11361)
    at async Promise.all (index 0)
    at async D.install (http://localhost:3000/workbox-07643d7a.js:1:10780)

It seems to be looking in the /public/pwa/ directory for the icons when they are in fact in the `/pwa/ directory.

My manifest.json is also in the /pwa/ directory and looks like this:

{
  "name": "Name",
  "short_name": "Name",
  "description": "description",
  "dir": "auto",
  "lang": "en-US",
  "display": "standalone",
  "orientation": "any",
  "start_url": "/?homescreen=1",
  "background_color": "#fff",
  "theme_color": "#000",
  "icons": [
    {
      "src": "/pwa/android-chrome-36x36.png",
      "sizes": "36x36",
      "type": "image/png"
    },
   ...
  ]
}

How come this it's looking for icons in the starting in public?

Many thanks for any advice?

I'm using version 2..1.2 of this module with next 9.2.1

Homepage is not triggering cache repopulation

Hello, I'm having an issue with the service worker specifically when opening the homepage (index.js) of my app.

The request to localhost:7777 is completely relying on the offline cache, breaking some functionality that is dependent on cookies.

On the other hand, when visiting any other page (/login, /shop, etc.) the request by the Service Worker's install handler to populate the offline cache is made every time, which should also be the behavior of the homepage.

Homepage (no call):
Screen Shot 2020-05-08 at 14 27 43

Any other page:
Screen Shot 2020-05-08 at 14 28 30

How could I replicate this behavior also on the homepage? I'm not sure if this is a bug or something I should configure.

Info:

  • the app doesn't have a custom server.js file
  • in next-pwa's config I only added dest: 'public'

When service worker is modified, latest SW is not getting updated in the client.

Set up:
We are using workbox in injectManifest mode with next-pwa.

Context:
There is an offline fallback view which should be precached.
Inside my custom service worker (srcSW), I am achieving as

const CACHE_NAME = "offline-html";
const FALLBACK_HTML_URL = "/offline";
self.addEventListener("install", async event => {
event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.add(FALLBACK_HTML_URL)))
})
myPWAConfig looks like:

return {
disable: process.env.NODE_ENV !== "production",
register: true,
scope: "/",
sw: "/sw.js",
swSrc: "./swSrc.js",
maximumFileSizeToCacheInBytes: mb1,
include: [/(pages/offline.js)$/], // same offline page
exclude: [/.*.map$/],
}
Each time I do an update in view/offline.js the service worker is not getting updated on client refresh. I have to do an explicit service worker update.

Outside next-pwa I was trying the same with work-box build and it was working as expected.

"globIgnores" is not a supported parameter

I'm trying to have more control over the routes and precached files. I'm using GenerateSW strategy to generate my service worker, and according to the workbox documentation, I could pass the globIgnores parameter to the generateSW class so that I could match files to always exclude when generating the precache. But I'm running into this error:

image

New version 2.1.3 causes error with dotenv in dev mode (PWA disabled)

As I have been following this project from version 2.1.2, everything works just fine.
But after upgrading to version 2.1.3, I have this error only in dev mode (PWA suppport is disabled)

Module not found: Can't resolve 'fs' in '..../node_modules/dotenv/lib'

Production mode is okay. Could you check it?

next.config.js (no custom webpack config)

withPWA({
      pwa: {
        register: false,
        skipWaiting: false,
        dest: 'public'
      },
    })
"dotenv": "^8.2.0",
"next": "^9.2.0",
"next-pwa": "^2.1.3",

Next 9 example fails on Now deployment

Hey @shadowwalker, thanks for your awesome package! I tried deploying the Next 9 example to Now without any changes however the build failed with the following errors. Any ideas what's going on here?

> [PWA] generate precache manifest in /tmp/625de824/public
> [PWA] ====== compile server ======
> [PWA] auto register service worker with: /tmp/625de824/node_modules/next-pwa/register.js
Compiled with warnings.

You're using the following Workbox configuration options: [globDirectory, globPatterns]. In Workbox v3 and later, this is usually not needed. Please see https://goo.gl/EQ4Rhm for more info.

Page            Size     Files  Packages
┌ ⚡ /           490 B        0         4
├   /_app       2.04 kB      0         4
├   /_document
└   /_error     2.11 kB      0         3

λ  (Lambda)       page was emitted as a lambda (i.e. getInitialProps)
⚡  (Static File)  page was prerendered as static HTML

preparing lambda files...
Creating lambda for page: "_error.js"...
Created lambda for page: "_error.js"
{ Error: ENOENT: no such file or directory, open '/tmp/625de824/public/precache-manifest.2a9f4cd71ccfaff43ed0033cc1b291af.js'
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/tmp/625de824/public/precache-manifest.2a9f4cd71ccfaff43ed0033cc1b291af.js' }
done

Thanks,
Kris

Next-9+ example not working

Hi thank you for working in this library.
I've been trying to implement it for a quick prototype of an app I'm building and I can't get the sw to work.
So I forked the example on next-9+, which I've been following, and after running npm install , npm run build and npm start the sw is not there for lighthouse or if I run navigator.serviceWorker I get undefined.
Could this be a bug?

How can i prevent import duplicated files ?

I use the next-optimized-images module who convert to webp on the fly all my images.

The problem is the service worker import twice file.. like this :
Capture d’écran 2020-04-30 à 15 35 57
the .jpg and the .webp version

I would like to reduce the size of cache data and import all my images, except .wepb

In my next.config.js I tried something like that:

module.exports = withPlugins(
  [
    [
      withPWA,
      {
        pwa: {
          dest: "public",
          disable: process.env.NODE_ENV === "development",
          publicExcludes: ["([a-zA-Z0-9\\s_\\\\.\\-\\(\\):])+(.webp)$"]
        }
      }
    ],
    [...]
  ],
  nextConfig
);

But it seems it doesn’t work.

However I tested my regex expression and it works well here: https://regex101.com/r/CRiDxt/1

Someone would have an idea to solve my problem ? Thank you everyone

delete cookies from service worker

Hello, thanks for the project. I have a question about how to delete cookies from the service worker for auth sessions?

I have a cookie based session and the logout works fine without next-pwa, but when I use the serviceworker the user never gets logged out.

Do you have any information on how to delete the session? thanks

Install PWA in Chrome for Android

Hi! This is more a doubt rather than a bug, and i was wondering if you could maybe help me. Currently i started to use this lib and i have no issues with it. I've also run audits inside Chrome regarding PWA and i have no errors at all; still, there's no message to install the PWA in Chrome for Android. Do you know what this could be? Is a normal behavior?

Thanks a lot!

Fetch event handlers must be added during the worker script’s initial evaluation

I've added next-pwa, configured next.config.js:

  if (process.env.NODE_ENV === 'development') {
   plugins = withPlugins([
     withCss,
     [withFonts, { enableSvg: true }],
     [optimizedImages, optimizedImagesConfig]
   ], opts)
 } else {
   plugins = withPlugins([
     withPWA,
     withCss,
     [withFonts, { enableSvg: true }],
     [optimizedImages, optimizedImagesConfig]
   ], opts)
 }

And Firefox triggered on the console:

Fetch event handlers must be added during the worker script’s initial evaluation. ./workbox-eb42688b.js:1:13052
Fetch event handlers must be added during the worker script’s initial evaluation. ./workbox-eb42688b.js:1:796

I've configured my next project with express, and these are the lines I added to find sw.js:

    if (process.env.NODE_ENV !== 'development') {
      server.get(['/sw.js', '/workbox-*', '/service-worker.js'], (req, res) => {
        const {
          path: pathname
        } = req
        const filePath = path.join(__dirname, '.next', pathname)
        app.serveStatic(req, res, filePath)
      })
    }

I've configured CSP:

      csp = `default-src 'self'; script-src 'self' '${cspHashOf(
        NextScript.getInlineScriptSource(this.props)
      )}'`
      csp += ' \'unsafe-eval\' https://www.gstatic.com https://www.googletagmanager.com https://www.google-analytics.com'
      csp += ' https://recaptcha.net https://maps.googleapis.com https://maps.gstatic.com'
      csp += ' https://www.google-analytics.com https://ajax.googleapis.com https://www.google.com'
      csp += ' https://google.com https://gstatic.com https://ssl.google-analytics.com'
      csp += ' https://www.youtube.com https://s.ytimg.com https://connect.facebook.net;'
      csp += ' img-src * data: \'unsafe-inline\';'
      csp += ' style-src \'self\' \'unsafe-inline\' https://fonts.googleapis.com https://fonts.gstatic.com;'
      csp += ' font-src \'self\' https://fonts.gstatic.com data:;'
      csp += ' frame-src https://www.google.com https://www.youtube.com https://www.facebook.com'
      csp += ' https://s-static.ak.facebook.com; object-src \'self\'; connect-src *'

These are my dependencies:

  "dependencies": {
    "@babel/core": "7.8.7",
    "@babel/runtime": "7.8.7",
    "@fortawesome/fontawesome-svg-core": "1.2.27",
    "@fortawesome/free-brands-svg-icons": "5.12.1",
    "@fortawesome/free-regular-svg-icons": "5.12.1",
    "@fortawesome/free-solid-svg-icons": "5.12.1",
    "@fortawesome/react-fontawesome": "0.1.9",
    "@zeit/next-css": "^1.0.2-canary.0",
    "axios": "0.19.2",
    "body-parser": "1.19.0",
    "boom": "7.3.0",
    "compression": "1.7.4",
    "connect-session-sequelize": "6.1.1",
    "cookie-parser": "1.4.4",
    "d3-format": "1.4.3",
    "dotenv": "8.2.0",
    "enquire-js": "^0.2.1",
    "express": "4.17.1",
    "express-robots-txt": "0.4.1",
    "express-session": "1.17.0",
    "file-loader": "5.1.0",
    "formik": "2.1.4",
    "get-video-id": "3.1.4",
    "google-map-react": "^1.1.6",
    "helmet": "3.21.3",
    "html-to-react": "1.4.2",
    "http-proxy-middleware": "1.0.1",
    "imagemin-gifsicle": "7.0.0",
    "imagemin-mozjpeg": "^8.0.0",
    "imagemin-optipng": "7.1.0",
    "imagemin-svgo": "7.1.0",
    "isomorphic-unfetch": "^3.0.0",
    "lodash.shuffle": "^4.2.0",
    "lqip-loader": "^2.2.0",
    "lusca": "^1.6.1",
    "mobile-detect": "1.4.4",
    "morgan": "^1.9.1",
    "next": "9.2.2",
    "next-compose-plugins": "2.2.0",
    "next-fonts": "^1.0.3",
    "next-optimized-images": "2.5.5",
    "next-pwa": "^2.2.0",
    "nookies": "^2.0.8",
    "prop-types": "15.7.2",
    "pure-react-carousel": "1.25.2",
    "rc-drawer": "3.1.3",
    "rc-slider": "9.2.2",
    "rc-switch": "^1.9.0",
    "react": "16.13.0",
    "react-animated-css": "1.2.1",
    "react-autosuggest": "^9.4.3",
    "react-countup": "4.3.3",
    "react-detect-offline": "2.4.0",
    "react-dom": "16.13.0",
    "react-ga": "2.7.0",
    "react-iframe": "1.8.0",
    "react-js-pagination": "3.0.3",
    "react-loader-spinner": "3.1.5",
    "react-loading": "^2.0.3",
    "react-masonry-css": "1.0.14",
    "react-modal": "3.11.2",
    "react-modal-video": "1.2.3",
    "react-no-ssr": "^1.1.0",
    "react-parallax": "3.0.3",
    "react-scroll": "1.7.16",
    "react-share": "4.0.1",
    "react-slick": "0.25.2",
    "react-sticky-el": "1.1.0",
    "react-text-truncate": "0.16.0",
    "react-toastify": "5.5.0",
    "react-youtube": "7.9.0",
    "reaptcha": "1.7.2",
    "rotating-file-stream": "2.0.2",
    "sequelize": "5.21.5",
    "slugify": "1.4.0",
    "sqlite3": "4.1.1",
    "universal-cookie": "4.0.3",
    "url-parser": "^0.0.1",
    "yup": "0.28.2"
  },
  "optionalDependencies": {
    "fsevents": "*"
  },
  "devDependencies": {
    "@babel/plugin-proposal-class-properties": "7.8.3",
    "@babel/plugin-proposal-decorators": "7.8.3",
    "@babel/plugin-proposal-object-rest-spread": "7.8.3",
    "@babel/plugin-transform-react-jsx-source": "7.8.3",
    "@babel/plugin-transform-runtime": "7.8.3",
    "@babel/preset-env": "7.8.7",
    "@babel/preset-react": "7.8.3",
    "@storybook/addon-actions": "5.3.14",
    "@storybook/addon-links": "5.3.14",
    "@storybook/addons": "5.3.14",
    "@storybook/react": "5.3.14",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "10.1.0",
    "babel-jest": "25.1.0",
    "babel-loader": "8.0.6",
    "eslint": "6.8.0",
    "faker": "^4.1.0",
    "husky": "4.2.3",
    "jest": "25.1.0",
    "snazzy": "^8.0.0",
    "standard": "14.3.1"
  }

The Node version: 12.16.1
The Next version: 9.2.2

is behind redirect

Hi everybody

When I use next-pwa i get this errors :

The script resource is behind a redirect, which is disallowed.

Uncaught (in promise) DOMException: Failed to register a ServiceWorker for scope ('https://digiscards.com/') with script ('https://digiscards.com/sw.js'): The script resource is behind a redirect, which is disallowed.

Any clue of how to fix it ?

Page caching issue

Hello there,
I have the same issue as #26

Here's the scenario.
I have a home page that uses getServerSideProps to call my API, fetch new posts, and render them. however, when data is changed it still shows the cached version of that page.
Another thing is I parse the request cookies inside getServerSideProps and then render the page based on some cookies. those also have this issue

Still not enough information, is it under dev or prod mode? How do you call your API, do you need > to refresh or call the API again to fetch the latest data?
@shadowwalker

Tested on production when https is present. And when https is not present it works just fine.

Here is my configuration

const path = require("path");
const withPWA = require("next-pwa");

module.exports = withPWA({
  pwa: {
    dest: "public",
    runtimeCaching: [
      {
        urlPattern: /^https:\/\/fonts\.(?:googleapis|gstatic)\.com\/.*/i,
        handler: "CacheFirst",
        options: {
          cacheName: "google-fonts",
          expiration: {
            maxEntries: 4,
            maxAgeSeconds: 365 * 24 * 60 * 60, // 365 days
          },
        },
      },
      {
        urlPattern: /^https:\/\/use\.fontawesome\.com\/releases\/.*/i,
        handler: "CacheFirst",
        options: {
          cacheName: "font-awesome",
          expiration: {
            maxEntries: 1,
            maxAgeSeconds: 365 * 24 * 60 * 60, // 365 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: "StaleWhileRevalidate",
        options: {
          cacheName: "static-image-assets",
          expiration: {
            maxEntries: 64,
            maxAgeSeconds: 24 * 60 * 60, // 24 hours
          },
        },
      },
      {
        urlPattern: /\.(?:js)$/i,
        handler: "NetworkFirst",
        options: {
          cacheName: "static-js-assets",
          expiration: {
            maxEntries: 16,
            maxAgeSeconds: 24 * 60 * 60, // 24 hours
          },
        },
      },
      {
        urlPattern: /\.(?:css|less)$/i,
        handler: "StaleWhileRevalidate",
        options: {
          cacheName: "static-style-assets",
          expiration: {
            maxEntries: 16,
            maxAgeSeconds: 24 * 60 * 60, // 24 hours
          },
        },
      },
      {
        urlPattern: /\.(?:json|xml|csv)$/i,
        handler: "NetworkFirst",
        options: {
          cacheName: "static-data-assets",
          expiration: {
            maxEntries: 16,
            maxAgeSeconds: 24 * 60 * 60, // 24 hours
          },
        },
      },
      {
        urlPattern: /.*/i,
        handler: "NetworkFirst",
        options: {
          cacheName: "others",
          expiration: {
            maxEntries: 16,
            maxAgeSeconds: 24 * 60 * 60, // 24 hours
          },
        },
      },
    ],
  },
  webpack(config) {
    config.resolve.alias["#"] = path.resolve(__dirname, "src");
    return config;
  }
});

Support /public/ directory

For reference: vercel/next.js#7800 (comment)

Both sw.js and precache-manifest.*.js should go in the root directory. Next 9 adds support for root files (robots.txt, favicon.ico, etc.) with a /public/ directory (that will eventually replace /static/ too).

For now, a user wishing to use the /public/ directory feature must enabled by adding this snippet in next.config.js:

{
  experimental: { publicDirectory: true },
}

Not sure if the location of manifest.json is harcoded into /static/ but we might want ot look in /public/ too.

wrong precacheAndRoute entry in sw.js for dynamic routes

Demo

pwa-precache-error

Please open this GIF in new window to proper view

as you can see when hitting precached route for the first time in offline scenario leaves page non interactive due to supported js file resulting in 404

Minimal Reproducable Example

https://github.com/harshzalavadiya/next-pwa-precache-bug

Live Example

https://onwd3.now.sh/

currently generated sw.js file has non encoded square brackets in precacheAndRoute as shown below
image

but after manually editing sw.js entry like below it works
image

p.s. basically my end goal was to precache /hello/[name] and make it work dynamically with any route but seems it's not diretly possible so I'm adding /hello/xyz route to cache at runtime

Using webpack alias w/ next-pwa `_app.tsx` causes error

First of all thank you for making amazing next-pwa plugin

webpack aliases works fine when using it in other files w/ using next-pwa but when we use any alias import in _app.tsx causes compilation error

[ error ] ./src/pages/_app.tsx
Module not found: Can't resolve '@components/@core/container' in '/home/x/git/biodiv-ui-next/src/pages'

Error was introduced in latest release, worked fine in 2.1.2 w/ latest next

Minimal reproduction project
https://github.com/harshzalavadiya/next-pwa-error-app-tsx

OS linux
NodeJS 12.16.0 LTS
Yarn 1.x Latest

offline mode not work!

Hi
i cache all pages in next.config.js by NetworkFirst strategy and it works well
but when i navigate to second page and set the offline mode in application tab,i expect that when i refresh the second page it works in offline mode but it doesnot work !
but when i navigate to second page and refresh the second page then i set the offline mode in application tab ,and refresh the second page that work in offline mode as well !
(when i refresh the second page before set offline mode...the cache manager work goood and if i dont refresh the second page the cache manager doesnt load second page in offline mode)

please help...

Excluding some pages based on urls or patterns.

Hi thanks for this great package.

I have a quick question. Assuming I want to exclude some pages from being cached. Like let's say /dashboard and/or /dashboard/* is that possible?.

If yes, could you point me in the right direction. Thank you. I am new to pwa and offline all.

Thanks in advance.

Script loading does not work when using dynamic routing

I use Next.js 9+ with dest: 'public'
I have a page path: /pages/communities/[communityId]/post/index.tsx

But when navigating through the pages, the script loading path looks like:
Prod mode: _/next/static/8Lf71cZLXHJd_0V-D30mA/pages/communities/1/post/index.js - 404 error status.
Dev mode: _/next/static/8Lf71cZLXHJd_0V-D30mA/pages/communities/%5BcommunityId%5D/post/index.js - 500 error status.

The problem is that id is present in the script request path.

GenerateSW has been called multiple times

Hello,
I recently setup next-pwa on by next.js app, and when using running in development next dev, every new page load (for that development session) will see GenerateSW being called again. This ends up being annoying as it causes lag on page navigation, is disruptive in the console, and causes a new sw.js to be generated all the time, even though no changes have been made (I don't even have a custom serviceworker setup right now at all.

On the live app (Hosted & compiled by vercel/ZEIT), no GenerateSW error appears in the console. I'm running next.js ^9.3.3 and next-pwa ^2.4.0.

The error message reads:
[ warn ] GenerateSW has been called multiple times, perhaps due to running webpack in --watch mode. The precache manifest generated after the first call may be inaccurate! Please see https://github.com/GoogleChrome/workbox/issues/1790 for more information.

Since I'm totally brand new to serviceworkers and PWA in general, I have no idea how to get around this issue.

Uncaught (in promise) TypeError: Failed to fetch

I'm using next.js 9+ and i'm getting an error when the page is loaded (in production).

Uncaught (in promise) TypeError: Failed to fetch

The error occurs in sw.js. Also, the service worker does not work.

how access localStorage in custom worker file for library (@uppy/golden-retriever)?

I require('@uppy/golden-retriever/lib/ServiceWorker') In /worker/index.js

then, Error occured ( In dev mode, also in build and deploy, error occured, too)

ReferenceError: localStorage is not defined at findUppyInstances (/home/hwanggyeongchan/workspace/sr-client/node_modules/@uppy/golden-retriever/lib/MetaDataStore.js:9:23) at Function.cleanup (/home/hwanggyeongchan/workspace/sr-client/node_modules/@uppy/golden-retriever/lib/MetaDataStore.js:85:23) at new MetaDataStore (/home/hwanggyeongchan/workspace/sr-client/node_modules/@uppy/golden-retriever/lib/MetaDataStore.js:46:21) at new GoldenRetriever (/home/hwanggyeongchan/workspace/sr-client/node_modules/@uppy/golden-retriever/lib/index.js:44:27) at Uppy.use (/home/hwanggyeongchan/workspace/sr-client/node_modules/@uppy/core/lib/index.js:1305:18) at Object.NVXP (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:714:4) at __webpack_require__ (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:23:31) at Object.Nhdc (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:2742:14) at __webpack_require__ (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:23:31) at Module.cha2 (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:3442:18) at __webpack_require__ (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:23:31) at Object.0 (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:251:18) at __webpack_require__ (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:23:31) at module.exports./jkW.Object.defineProperty.value (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:91:18) at Object.<anonymous> (/home/hwanggyeongchan/workspace/sr-client/.next/server/static/N54wyu3Jm5658qcLZSY8x/pages/_app.js:94:10) at Module._compile (internal/modules/cjs/loader.js:776:30)

So can I access localStorage in custom worker ?
Or is there any other solution for accessing problem to localStorage

path.join is used to join non-URLs which breaks `now dev` on Windows

Running now dev on a next-pwa enabled app on Windows will result in an unbootable app, because scope will incorrectly be generated as "\", which will be parsed as an unterminated string. This is because many places in the code concatenate URLs with path.join, when they probably just want [someOther, thing].join('/')

Cache returning old version (revision md5 uses file name instead of file content)

I noticed that my cache was not getting updated after changing some images. After a few hours of digging I noticed that the ?WB_REVISION is never changing. Some more digging... the revision is only taking into consideration the file name and not the content to calculate the md5. This seems like a bug to me, can someone with more experience confirm?

Sent PR in case I am not around when you see this.

// Current code in https://github.com/shadowwalker/next-pwa/blob/master/index.js
const getRevision = file => crypto.createHash('md5').update(Buffer.from(file)).digest('hex')
// Seems to me like it should use fs.readFileSync(file) instead of Buffer.from(file)
const getRevision = file => crypto.createHash('md5').update(fs.readFileSync(file)).digest('hex')

How to integrate next-pwa with SASS?

Hi, I have a compilation error because I can't find how to integrate next.config with my next sass, can you help me a little? Thank you.

const withPWA       = require('next-pwa');
const withSass      = require('@zeit/next-sass');
module.exports      = withPWA(withSass());

This returns me a sass error:

Module parse failed: Unexpected character '@' (2:0)

Maybe it's a mistake of mine, but I haven't managed to insert multiple configurations to my next.config

How can I avoid all API request from being cached.

I tried something from issue #46

But it didn't help.
I updated the regex to /\/api\/.*/g

runtimeCaching: [
  ...
  {
    urlPattern: /\/api\/.*/g,
    handler: "NetworkFirst",
  },
  ...

]

It would be helpful if I could exclude all network request matching regex /\/api\/.*/g
Thanks.

Cache SSG pages

We have about 120 SSG pages in our application which isn't too much data to transfer over the network. It would be nice to add all SSG JSON data to the service worker so every page is cached automatically.

It might be interesting to introduce some limits as how much it should be able to cache here, for example, we only the x-first pages of getStaticPaths for a page for example.

bad-precaching-response!!!

Hi!
first thanks for this awesome libary
issue:service worker installed on dev mode successfully but when i deploy to Now Server,registering the service worker failed...!
while fetching .map file!
Capture
whats the problem?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.