Open 2manoj1 opened 1 year ago
After remove useCallback and made some changes check its working. https://github.com/2manoj1/nextjs-firebase-example/commit/0f193f5473ea38864816a4925a280aa8f54dddcf
Why this occurred now. any config changes require? How fix this issue?
Hi @2manoj1, thanks for reporting this issue. I was able to reproduce the behavior you mentioned. Let me check what we can do for this issue or bring someone here that can provide more context about it. Iβll update this thread if I have any information to share.
This issue still coming in first time. Also clear cache way. My workaround not working. Look like service worker firebase having issues.
@jbalidiong any solutions? Any workaround how to fix this issue. In Production also coming this issue.
@2manoj1, apologies for the delay. I have discussed this with our FCM team and this is working as intended. The 404 that you've received from this screenshot is due to the indexDB being cleared and then there will be no token(s) to be deleted. With your app, I experience the same behavior. However, after receiving the warning, a new token will be created. Is this not the same as yours? Are you receiving any other errors aside from the previous one or you are not able to receive a new token?
@jbalidiong This issue still persist. On new device try to getToken first time. Its error coming and token is null.
Also I tried clear storage and unregister service worker or clear everything. Its reproducible. Without 2 refresh this cause issue.
Look like before ready service worker calling. await swRegistration.serviceWorker.ready
missing before call subscribe.
I am unfamiliar w/ next but your repo doesn't seem to have a required firebase-messaging-sw.js file https://github.com/search?q=repo%3A2manoj1%2Fnextjs-firebase-example%20firebase-messaging-sw.js&type=code.
Per public doc https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token: "FCM requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token. You can add meaningful content to the file later in the client setup process".
(Also btw, you are leaking your api key in the repo shared. Maybe you'd like to obfuscate or hide it. )
@zwu52 sw file already in public folder please check. public/firebase-messaging-sw.js
API key not required to hide. Watch official firebase video. If I hide also SPA app expose in source. Don't worry about key.
My hypothesis is some intricacies on how next loads scripts cause the incompatibilities between the SDK & the code.
I suspect it's not a race issue you suspected "Look like before ready service worker calling. await swRegistration.serviceWorker.ready missing before call subscribe." given the registration call is a blocking call here https://github.com/firebase/firebase-js-sdk/blob/master/packages/messaging/src/helpers/registerDefaultSw.ts#L27.
Another pointer to the loading of the sw path here https://github.com/firebase/firebase-js-sdk/blob/master/packages/messaging/src/helpers/registerDefaultSw.ts#L28. The SDK is expecting the sw script to live in a root directory.
Can you try to play around the SDK & figure out how to make it compatible?
I am trying but not able to figure out how use my fork version.
@jbalidiong are get chance to see this https://github.com/firebase/firebase-js-sdk/issues/7575#issuecomment-1693877829 ?
I have the same problem, but with the flutter package:
When I run the app for the first time that's when I get that error, but if I reload the permissions my app works fine, this is where the app fails:
I am following the process correctly, first I made the permissions request and then I got the token.
And well, this is a new error of my application, this application was working correctly, I did not change anything and now I have this error.
Workaround - if fail call again get token. 3 Retry I did and that's way solve the fix
Same issue here https://github.com/firebase/firebase-js-sdk/issues/7693
i have the same issue.
I get this error: "Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker " when I run my Flutter app for the first time on Chrome browser, but if I restart the app or refresh the browser page, the error disappears.
is there any solution for that?
I noticed this happened when I used Chrome, I switched to Firefox and I didn't have it anymore with exactly the same code.
But after some code changes I made it work again in chrome, not even sure why exactly or how it got fixed.
Same issue here, I get this error every time I clear the website data and reset the permissions.
Error sending user token DOMException: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
same issue here. It thrown error always the first time, after reload works fine. I'm using Opera
Same issue here with Flutter 3.16
This setup seems to avoid the no active Service Worker
error for a Flutter based Firebase Messaging web app in my limited testing:
requestPermission()
must now be called separately & before getToken()
, getToken()
no active Service Worker
error.Previously just a getToken()
call would automatically request push notification permission if it hadn't already been done and then the token would be retrieved directly after without error.
Even the example app on Github by the Firebase team has the same no active Service Worker
error:
https://github.com/firebase/flutterfire/tree/master/packages/firebase_messaging/firebase_messaging/example
(The example app tries to getToken()
on startup without user interaction. See the below run output.)
[xxxx:~/docker/flutterfire/packages/firebase_messaging/firebase_messaging/example]
$ flutter run -d chrome
Launching lib/main.dart on Chrome in debug mode...
Waiting for connection from debug service on Chrome... 28.8s
This app is linked to the debug service: ws://127.0.0.1:49500/L0CHcF9eCjo=/ws
Debug service listening on ws://127.0.0.1:49500/L0CHcF9eCjo=/ws
π₯ To hot restart changes while running, press "r" or "R".
For a more detailed help message, press "h". To quit, press "q".
A Dart VM Service on Chrome is available at: http://127.0.0.1:49500/L0CHcF9eCjo=
The Flutter DevTools debugger and profiler on Chrome is available at: http://127.0.0.1:9101?uri=http://127.0.0.1:49500/L0CHcF9eCjo=
Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 327:10 createErrorWithStack
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 337:28 _throw
dart-sdk/lib/core/errors.dart 120:5 throwWithStackTrace
dart-sdk/lib/async/zone.dart 1386:11 callback
dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 181:7 <fn>
Application finished.
Has there been some JavaScript added to FlutterWeb/FirebaseCore/FirebaseMessaging that prevents the service worker from being "fully ready" until there has been some user interaction with the web app?
(I use quotes on "fully ready" as the ServiceWorker is marked as ready if you check the JS console, but will still throw the error if you haven't interacted with the app before making the getToken()
call. To check I added a navigator.serviceWorker.ready.then(reg => console.log("Service Worker Ready"));
line to index.html after the const app = initializeApp(firebaseConfig);
line.
As a test (using Flutter's Demo / "You have pushed the button this many times:" app on a new project), we can request push notification permission in main(), then call getToken() on a FloatingActionButton (FAB) onPressed handler and this will work consistently without any errors on first getToken()
request:
/// Request push notification permissions at app start
void main() async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await FirebaseMessaging.instance.requestPermission();
runApp(const MyApp());
}
Then in _MyHomePageState, get the token in _incrementCounter()
which is the onPressed handler for the FAB:
void _incrementCounter() {
getFCMToken(); // see definition below
setState(() {
_counter++;
});
}
The getFCMToken()
method above is:
Future<String?> getFCMToken() async {
print('Getting Fcm Token...');
fcmToken = await FirebaseMessaging.instance.getToken(vapidKey: "YourVAPIDKeyHeRe");
print('fcmToken: $fcmToken');
return fcmToken;
}
This works fine, even on first run, without the no active Service Worker
error.
The bizarre thing: if you call getToken()
without user interaction, you'll likely get the no active Service Worker
error. (The error isn't 100%, but pretty often, like 80%.)
For example, try to call getToken()
in initState()
of _MyHomePageState
, after the page is built:
@override
void initState() {
super.initState();
listenNotifications(context);
WidgetsBinding.instance.addPostFrameCallback((_) {
print('postFrameCallback, calling getFCMToken');
getFCMToken().then((tkn) => print('tkn: $tkn'));
});
}
This will likely throw the no active Service Worker
error.
Adding in a delay will likely still get you the error:
@override
void initState() {
super.initState();
listenNotifications(context);
Future.delayed(const Duration(seconds: 10)).then((_) => getFCMToken());
}
Any ideas on what's going on? I'm not familiar enough with the JS side of Flutter / Firebase to debug this deeper.
I'm using:
firebase_core: ^2.24.2
firebase_messaging: ^14.7.10
This is my Flutter doctor output:
$ flutter doctor -v
[β] Flutter (Channel stable, 3.16.5, on macOS 14.2.1 23C71 darwin-x64, locale en-US)
β’ Flutter version 3.16.5 on channel stable at /Users/xxxx/fvm/versions/stable
β’ Upstream repository https://github.com/flutter/flutter.git
β’ Framework revision 78666c8dc5 (4 weeks ago), 2023-12-19 16:14:14 -0800
β’ Engine revision 3f3e560236
β’ Dart version 3.2.3
β’ DevTools version 2.28.4
[β] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
β’ Android SDK at /Users/xxxx/Library/Android/sdk
β’ Platform android-33, build-tools 33.0.0
β’ ANDROID_SDK_ROOT = /Users/xxxx/Library/Android/sdk
β’ Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
β’ Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
β’ All Android licenses accepted.
[β] Xcode - develop for iOS and macOS (Xcode 15.1)
β’ Xcode at /Applications/Xcode.app/Contents/Developer
β’ Build 15C65
β’ CocoaPods version 1.11.3
[β] Chrome - develop for the web
β’ Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[β] Android Studio (version 2022.2)
β’ Android Studio at /Applications/Android Studio.app/Contents
β’ Flutter plugin can be installed from:
π¨ https://plugins.jetbrains.com/plugin/9212-flutter
β’ Dart plugin can be installed from:
π¨ https://plugins.jetbrains.com/plugin/6351-dart
β’ Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
[β] VS Code (version 1.85.1)
β’ VS Code at /Applications/Visual Studio Code.app/Contents
β’ Flutter extension version 3.80.0
[β] Connected device (2 available)
β’ macOS (desktop) β’ macos β’ darwin-x64 β’ macOS 14.2.1 23C71 darwin-x64
β’ Chrome (web) β’ chrome β’ web-javascript β’ Google Chrome 120.0.6099.234
[β] Network resources
β’ All expected network resources are available.
β’ No issues found!
mesmo erro.... alguma solução além do que foi dito pelo @ben-xx ?
i have the same issue.
I get this error: "Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker " when I run my Flutter app for the first time on Chrome browser, but if I restart the app or refresh the browser page, the error disappears.
is there any solution for that?
me too, but when try a test, the message on background works
I'm facing the same issue
same issue for me on flutter web latest firebase:
Uncaught (in promise) Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
everything work after page reload, so its just the first time
Hi guys,
Can you help me resolve this?
π Looks like a firebase js SDK issue, when I have the following service worker file.
/* eslint-disable no-undef */
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js');
const firebaseConfig = {
apiKey: "REDACTED_AS_ASKED_BY_OWNER",
authDomain: "REDACTED_AS_ASKED_BY_OWNERi",
projectId: "crafty-biplane-405403",
storageBucket: "REDACTED_AS_ASKED_BY_OWNER",
messagingSenderId: "REDACTED_AS_ASKED_BY_OWNER",
appId: "REDACTED_AS_ASKED_BY_OWNER",
measurementId: "REDACTED_AS_ASKED_BY_OWNER"
};
// eslint-disable-next-line no-undef
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
// eslint-disable-next-line no-undef
const messaging = firebase.messaging();
messaging.onBackgroundMessage(payload => {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
// self.registration.showNotification(notificationTitle, notificationOptions);
});
Hi guys,
Can you help me resolve this?
π Looks like a firebase js SDK issue, when I have the following service worker file.
/* eslint-disable no-undef */ importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js'); const firebaseConfig = { apiKey: "REDACTED_AS_ASKED_BY_OWNER", authDomain: "REDACTED_AS_ASKED_BY_OWNERi", projectId: "crafty-biplane-405403", storageBucket: "REDACTED_AS_ASKED_BY_OWNER", messagingSenderId: "REDACTED_AS_ASKED_BY_OWNER", appId: "REDACTED_AS_ASKED_BY_OWNER", measurementId: "REDACTED_AS_ASKED_BY_OWNER" }; // eslint-disable-next-line no-undef firebase.initializeApp(firebaseConfig); // Retrieve firebase messaging // eslint-disable-next-line no-undef const messaging = firebase.messaging(); messaging.onBackgroundMessage(payload => { console.log('Received background message ', payload); const notificationTitle = payload.notification.title; const notificationOptions = { body: payload.notification.body, }; // self.registration.showNotification(notificationTitle, notificationOptions); });
π Not the perfect solution
So I could not solve this, but temporarily I show try...catch
the error & check the error message
. If it has this or something similar, I proceed to get the FCM Token generated again from firebase (may be in 1000ms).
@arc-prvh check this comment https://github.com/firebase/firebase-js-sdk/issues/7575#issuecomment-1711705543
When fail retry call again - I did 3 times retry logic. Its working, I am using in prod. No solution from FCM team yet
No solution for this issue?
So one way of doing this is waiting for the browser notification. Once received, just refresh the browser from javascript. Tell the user "configuring things in the background". That said, also pay attention to the UX part of the app. If you are doing something business critical do not just refresh anything. Wait for the user the next time they come. Best Regards,
Anweshan Roy Chowdhury, @.***) Full Stack Developer - Level 1, Pravaah Consulting Inc.
On Fri, Mar 29, 2024 at 4:59β―PM Dat Vu @.***> wrote:
No solution for this issue?
β Reply to this email directly, view it on GitHub https://github.com/firebase/firebase-js-sdk/issues/7575#issuecomment-2027108740, or unsubscribe https://github.com/notifications/unsubscribe-auth/A5NFSBHK7ZWBGOKPOSZW3HLY2VGDDAVCNFSM6AAAAAA3X74SSWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDAMRXGEYDQNZUGA . You are receiving this because you were mentioned.Message ID: @.***>
any solution for this problem? the workarounds are not reliable
(working on flutter web)
any news ?
Have you got firebase-messaging-sw.js file in public directory? According to https://stackoverflow.com/a/71339854
FCM requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token. You can add meaningful content to the file later in the client setup process.
I know that main problem was different, but solution worked for me. After create empty firebase-messaging-sw.js file in public problem with service workers was gone.
i have the same issue.
I get this error: "Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker " when I run my Flutter app for the first time on Chrome browser, but if I restart the app or refresh the browser page, the error disappears.
is there any solution for that? "I am also experiencing the same issue. Please let me know if anyone has found a solution for it."
i have the same issue. I get this error: "Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker " when I run my Flutter app for the first time on Chrome browser, but if I restart the app or refresh the browser page, the error disappears. is there any solution for that? "I am also experiencing the same issue. Please let me know if anyone has found a solution for it."
Try my solution here: https://github.com/firebase/firebase-js-sdk/issues/7693#issuecomment-2077118457
It can be fixed by waiting for the serviceWorker to be ready:
await navigator.serviceWorker.ready
const token = await getToken(options);
Hi @2manoj1,
Can you see if your issue is fixed by waiting for the server worker to full initialize, as suggested above by @dyabol and @ajmal-penny?
Thanks!
@DellaBitta I work with workaround https://github.com/firebase/firebase-js-sdk/issues/7575#issuecomment-1711705543
https://github.com/firebase/firebase-js-sdk/issues/7575#issuecomment-1693877829
Tried that but no luck so I added 3 retry logic. I think this should be added in lib code level.
Was tried this before https://github.com/2manoj1/firebase-js-sdk/pull/1
@DellaBitta the proposed fix, await navigator.serviceWorker.ready
, does not fix the problem.
I can confirm this, since I experienced the issue multiple times already, and yet again, with the above mentionned fix, it didn't work. When getToken()
was called, even though I called await navigator.serviceWorker.ready
just before, I did get the 'no service worker' error and had to try again twice to get the token.
I too, believed this would work and I actually thought the problem was fixed after maybe 20 or 30 tries, but the problem eventually showed up once again, meaning await navigator.serviceWorker.ready
is not sufficient or reliable enough.
It can be fixed by waiting for the serviceWorker to be ready:
await navigator.serviceWorker.ready const token = await getToken(options);
@ajmal-penny this is not sufficient to get rid of the error. You may still get 'no service worker' errors. I've launched hundreds of debug sessions the last few days, and this fix does not appear to be 100% reliable, I'm afraid.
@DellaBitta Using await navigator.serviceWorker.ready is not sufficient nor did it work in my case. The "I hope it passes on the third try" solution is not acceptable for me. Based on what's in the SW documentation (https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/statechange_event) I find out what the state of the SW is, if it's not activated, I register the "statechange" event and wait until the SW is activated, then call getToken. See https://github.com/firebase/firebase-js-sdk/issues/7693#issuecomment-2077118457 nothing magical
@dyabol thanks for the clarification. Are you calling the code shown in https://github.com/firebase/firebase-js-sdk/issues/7693#issuecomment-2077118457:
@andynewman10 I use https://vite-pwa-org.netlify.app/frameworks/react to register SW in my project so I don't know if this library implements something similar, but I don't use await navigator.serviceWorker.ready in my code.
@dyabol I've implemented your method yesterday and launched debug sessions with it maybe 30-40 times. On one occasion, this morning, it did fail.
Again, this method is not reliable enough.
@andynewman10 Do you have an example implementation or reproduced bug somewhere? I would be happy to help you, I have been using this solution in my application with 100% success for several months. Alternatively, if there is a flaw in the solution, I would like to know about it. Thx
@dyabol I'm using Flutter. I translated your code, but there still are (very rare) situations where this code ends up with a 'no service worker' issue:
Future<bool> waitServiceWorker() async {
final swr = await web.window.navigator.serviceWorker.getRegistration().toDart;
if (swr == null) {
return false;
}
web.ServiceWorker? sw;
if (swr!.installing != null) {
sw = swr!.installing;
} else if (swr!.waiting != null) {
sw = swr!.waiting;
} else if (swr!.active != null) {
sw = swr!.active;
}
if (sw != null) {
if (sw.state == 'activated') {
return true;
}
var completer = Completer<bool>();
sw.onstatechange.add((web.Event e) {
if ((e.target as web.ServiceWorker).state == 'activated') {
completer.complete(true);
}
}.toJS);
await completer.future;
await web.window.navigator.serviceWorker.ready.toDart;
return true;
}
return false;
}
@andynewman10 I have no experience with Flutter, but aren't "service worker not activated" and "no service worker" two different problems? Don't you rather have a problem somewhere in the SW registration?
@dyabol my apology, I meant 'no active service worker'. Sorry about this. I am checking if the exception string raised by FirebaseMessaging.instance.getToken
contains 'no active service worker' and, if this is the case, I start again.
@dyabol the next time I experience the issue, I'll try to paste here logging information. I added log entries before and after getToken, when an exception is raised, and at various locations inside the above function.
I have another big issue with getToken
- it sometimes takes 30+, up to 160 seconds to return a token, while I am developing over localhost. Have you observed that too? Not sure if this is linked yet but I am actively investigating. Will probably be worth another issue report. With the exact same Dart code, Android and iOS have zero problems, and I really mean zero.
Operating System
MacOS
Browser Version
All browser
Firebase SDK Version
10.2.0
Firebase SDK Product:
Messaging
Describe your project's tooling
Nextjs 13 with Page setup. Example Repo -> https://github.com/2manoj1/nextjs-firebase-example/tree/main
Describe the problem
Same problem as https://github.com/firebase/firebase-js-sdk/issues/5797 Sometimes calling messaging getToken returns the error: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker. It seems to occur on the first page load and clear storage with unregister sw, when the user refreshes the notifications work and there's no error anymore.
Steps and code to reproduce issue