Next.js Discord

Discord Forum

App router, Service Workers, Layout.tsx, and Firebase Cloud Messaging (FCM).

Unanswered
Siamese Crocodile posted this in #help-forum
Open in Discord
Siamese CrocodileOP
Hello,

I'm trying to use browser notifications with FCM.

It requires a service worker : firebase-messaging-sw.js

ChatGPT wants me to use useState from React for this line:

if ('serviceWorker' in navigator) {


It told me that i need to put it at the root / earliest part of my website so it has access to global view

My question is,

Is it ok to make a client component that wraps all the children.

As in:

export default function RootLayout({
children
}: PropsWithChildren) {

return (
<html lang="en">
<body>
<clientcomponentthatdoesServiceWorkers>
<Navbar />
<main>
{children}
</main>
<Footer />
<clientcomponentthatdoesServiceWorkers>
</body>
</html>
);



So is it ok to wrap every thing with a client component. Would this be good practice. Also Service Workers in general.

Why Nextjs Docs not have anything about it?

8 Replies

Siamese CrocodileOP
ALSO I SOLVED IT
It turns out my Footer is a client component. And since that is in layout.tsx and is rendered everytime i put the useState for service worker there
THIS WORKS 🙂 : useEffect(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then(registration => {
console.log('Service Worker Registered', registration);
})
.catch(err => {
console.error('Service Worker Registration Failed', err);
});
}
}, []);
its ok to wrap everything with client compont given that you pass server component into the child of the client component
Siamese CrocodileOP
i meant service workers when it came to documentation, only could find blogposts for pages router. thank you!
Oh my bad
Siamese CrocodileOP
👍