Why is workbox not triggering and installing the service worker - create-react-app

I have used npx create-react-app to create a PWA. I changed the unregister to register but the service worker is not installing when the code is run on vercel.com
https://github.com/kristiannissen/grocery-monkey-javascript/blob/main/src/index.js#L43
serviceWorkerRegistration.register();
To test it on localhost I modified the serviceWorkerRegistration.js but even when running the react-scripts build and testing on 127.0.0.1 nothing happens.
serviceWorkerRegistration.js
if ("serviceWorker" in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
How to I make the service worker work when it is created using CRA?

Related

How to check if server build has been updated in SSR Nuxt application

I dont know how to solve the problem if SSR Nuxt app in browser is not compatible with server side build cause build has been updated. It means that user have old version of application in the browser and needs to refresh the page. I found something like this: https://dev-clone.nuxtjs.app/alejandroakbal/632139
So I have created pwa-update.js file in the plugins dir and register it in the nuxt.config.js.
But I dont see any console.log() in the console. Dont understand how to use it and if it is the right way to do it.
Implementaion looks like pwa-update.js
export default async (context) => {
const workbox = await window.$workbox;
if (!workbox) {
console.debug("Workbox couldn't be loaded.");
return;
} else {
console.log('Workbox has been loaded.'); // Dont see any message.
}
workbox.addEventListener('installed', (event) => {
if (!event.isUpdate) {
console.log('The PWA is on the latest version.');
return;
}
console.log('There is an update for the PWA, reloading...');
// window.location.reload();
});
};
nuxt.config.js
plugins: [
{ src: '~/plugins/pwa-update.js', mode: 'client' },
],
If you're regenerating your service worker using workbox during your development build process, a new service worker will be installed after every build. You can check this in your browser's dev tools. I believe the workbox generated service worker callls skipWaiting() in order to install new service workers immediately.
The client should get the new resources automagically because of webpack JS chunk name changes (assuming you're using webpack, the JS chunks it generates get new names after every new build, for cache busting purposes) and service worker version changes (workbox auto-increments service worker version, busting that cache as well). In other words, SSR or not, you won't need to worry about any version mismatches so long as you're using workbox to generate your service worker for you.

Unifying localhost dev api server access for expo app across Android, IOS, and web?

I'm setting up a simple React Native learning app for several students on Expo, that also talks to an API server the student is learning to code.
The student's API server is run via node server.js, and serves on localhost:3000 on the student's machine. It has nothing to do with expo.
I want students to be able to run their app via any of expo start --android, expo start --ios, or expo start --web, on the same machine that runs their API server. Each student runs from home on a different home wifi network, and doesn't necessarily know the ins and outs of ip addresses or networking.
When using expo start --web, we get CORS exceptions, unless we use the custom webpack.config.js work around (first create webpack.config.js via https://docs.expo.io/guides/customizing-webpack/, then put this in webpack.config.js):
const createExpoWebpackConfigAsync = require('#expo/webpack-config');
module.exports = async function(env, argv) {
const config = await createExpoWebpackConfigAsync(env, argv);
if (config.mode === 'development') {
config.devServer.proxy = {
'/**': {
target: {
host: 'localhost',
protocol: 'http:',
port: 3000,
},
secure: false,
changeOrigin: true,
logLevel: 'info',
},
};
}
return config;
};
This is great, because we can make api calls to ./end/point without knowing the student's ip address, and the webpack devServer launched by expo-cli effectively proxies around to http://localhost:3000/end/point on the student's development machine.
Meanwhile, for iOS and Android, I've found this snippet:
import Constants from "expo-constants";
const { manifest } = Constants;
const SERVER_URL = "http://"+manifest.debuggerHost.split(`:`).shift().concat(`:3000`)+"/";
and then using SERVER_URL when using fetch().
But, we're missing a unified solution that works agnostic of which environment we're in (web, ios, or android). The webpack proxy only appears to be on and work when using the expo web client (expo-cli doesn't launch webpack for ios or android), and the 2nd option (A) doesn't work out of the box on web and (B) would trigger a CORS exception anyway.
How can I elegantly write one bit of code, or otherwise set up the project for the students, so that (A) they don't need to know their dev machine's ip address, or what that means and (B) it will work regardless of whether they're in the web, android, or ios expo client?
Don't like this as an answer and would prefer someone who knows better to point out better, but this is what I ended up using that seems to work, at least in development:
// Some chatter that Contants.manifest needs to come from a different package?
import Constants from "expo-constants";
const { manifest } = Constants;
const SERVER_URL = (() => {
// TODO - put a "prod" api server somewhere
// Android / IOS - no CORS issue.
if (!!manifest.debuggerHost) {
return "http://"+manifest.debuggerHost.split(`:`).shift().concat(`:3000/`);
}
// Expo Web client, making use of webpack.config.js (see original question) for devServer proxy.
else {
return "./";
}
})();
...
fetch(SERVER_URL + 'some_endpoint/').then(...)

Electron Builder Vue cli 3 application on Windows throwing error registerStandardSchemes undefined

Background
We are building an Electron application and have been able to work on it, and build it using Linux and Mac OS. When we move it to a Windows machine in development or when build on a Mac OS machine then ran on the Windows machine, it fails.
When we follow the instructions here it says,
vue add electron-builder
yarn electron:serve
should run the application. On a fresh install using Windows this fails for us.
Problem
When we try and start the application on Windows we get an error,
TypeError
electron__WEBPACK_IMPORTED_MODULE_0__.protocol.registerStandardSchemes
is not a function
Example
This line comes with the boilerplate when we add Electron Builder to the app that seems to be throwing the error.
protocol.registerStandardSchemes(['app'], { secure: true })
It is being used like this,
import { protocol} from 'electron'
protocol.registerStandardSchemes(['app'], { secure: true })
// Helper to create our main view BrowserWindow
function createWindow() {
// Create the browser window.
win = new BrowserWindow({ width: 800, height: 600 })
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
}
What We Tried
When I console.log protocol the only key available is, registerSchemesAsPrivileged which is in the docs but not what came with the boiler and nor does it work. I can see at this page that the registerStandardSchemes is referenced in a paragraph but it is not well explained in it's own section like the rest of the methods on that page.
Question
What does one need to do to access the method, protocol.registerStandardSchemes(['app'], { secure: true }) when running an Electron-Builder application scaffold with Vue CLI 3 on Windows 10?
I recently had this issue - if you're just looking to get back to development, running vue add electron-builder again fixed it for me.

nuxt.render not working in production mode for Nuxt SPA

The following code runs in the standard Nuxt server/index.js just fine in development mode when starting up my SPA app.
// Init Nuxt.js
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
When deployed and in production mode, the build process is skipped (which is what I want) but nuxt.render() fails because it has not been initialized by builder.build().
I've tried everything I can think of and can't find a solution where it simply renders a pre-built app as it LOOKS like it is supposed to do.

Vue Cli 3 how to use the official PWA plugin ( Service Worker )

on my first vue project attempting to wrestle with the official PWA plugin ( https://github.com/yyx990803/register-service-worker ).
My specific problem: capturing the registered service worker and using it for anything. The github readme shows the exact file that is produced, and there seems to be zero documentation about how to work with this service worker once it is instantiated ( do I capture the registration instance? if so, how? )
I found this issue: https://github.com/vuejs/vue-cli/issues/1481
and am providing a better place to talk about this, as I haven't been able to find any example code or clear documentation about how to work with this.
If anyone has some sample code, please share. Vue and the new cli are incredible tools, documenting things like this is a necessary step forward to increasing the adoption of the platform
As already pointed out, it's more of a "service workers" issue than a "vue cli" one.
First of all, to make sure we're on the same page, here's what the boilerplate content of registerServiceWorker.js should look like (vue cli 3, official pwa plugin):
import { register } from 'register-service-worker'
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready () {
console.log(
'App is being served from cache by a service worker.\n'
)
},
cached () {
console.log('Content has been cached for offline use.')
},
updated () {
console.log('New content is available; please refresh.')
},
offline () {
console.log('No internet connection found. App is running in offline mode.')
},
error (error) {
console.error('Error during service worker registration:', error)
}
})
}
If you haven't changed the BASE_URL variable in your .env file, then it should correspond to the root of your vue app. You have to create a file named service-worker.js in the public folder (so that it's copied into your output directory on build).
Now, it is important to understand that all the code in the registerServiceWorker.js file does is register a service worker and provide a few hooks into its lifecycle. Those are typically used for debugging purposes and not to actually program the service worker. You can understand it by noticing that the registerServiceWorker.js file will be bundled into the app.js file and run in the main thread.
The vue-cli 3 official PWA plugin is based on Google's workbox, so to use the service worker, you'll have to first create a file named vue.config.js at the root of your project and copy the following code in it:
// vue.config.js
module.exports = {
// ...other vue-cli plugin options...
pwa: {
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'public/service-worker.js',
// ...other Workbox options...
}
}
}
If you already have created a vue.config.js file, then you just have to add the pwa attribute to the config object. Those settings will allow you to create your custom service worker located at public/service-worker.js and have workbox inject some code in it: the precache manifest. It's a .js file where a list of references to your compiled static assets is stored in a variable typically named self.__precacheManifest. You have to build your app in production mode in order to make sure that this is the case.
As it is generated automatically by workbox when you build in production mode, the precache manifest is very important for caching your Vue app shell because static assets are usually broken down into chunks at compile time and it would be very tedious for you to reference those chunks in the service worker each time you (re)build the app.
To precache the static assets, you can put this code at the beginning of your service-worker.js file (you can also use a try/catch statement):
if (workbox) {
console.log(`Workbox is loaded`);
workbox.precaching.precacheAndRoute(self.__precacheManifest);
}
else {
console.log(`Workbox didn't load`);
}
You can then continue programming your service worker normally in the same file, either by using the basic service worker API or by using workbox's API. Of course, don't hesitate to combine the two methods.
I hope it helps !
as an addition to the answer above: I wrote a small guide on how to go further and add some functionality to the custom service-worker, using the setup above. You can find it here.
Four main things to keep in mind:
configure Workbox in vue.config.js to InjectManifest mode, pointing the swSrc key to a custom service-worker file in /src
In this custom service-worker, some lines will be added automatically in the Build process for importing the precache-manifest and workbox CDN. Following lines need to be added in the custom service-worker.js file to actually precache the manifest files:
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
Listen to registration events in the registerServiceWorker.js file. You can use the registration object that is passed as first argument to the event handlers to post messages to the service-worker.js file:
...
updated(registration) {
console.log("New content is available; please refresh.");
let worker = registration.waiting
worker.postMessage({action: 'skipWaiting'})
},
...
Subscribe to messages in the service-worker.js file and act accordingly:
self.addEventListener("message", (e)=>{
if (e.data.action=='skipWaiting') self.skipWaiting()
})
Hope this helps someone.