Reputation: 1995
Since I configured my React app to be a PWA, I started having issues with google authentication.
When the user clicks on sign-in with Google, this endpoint is supposed to be hit:
// @route GET api/users/auth/google
// @desc Authenticate user using google
// @access Public
router.get(
"/auth/google",
passport.authenticate("google", {
scope: [
"email",
"profile",
"https://www.googleapis.com/auth/user.birthday.read",
"https://www.googleapis.com/auth/user.gender.read",
"https://www.googleapis.com/auth/user.addresses.read",
],
})
);
But, since the PWA uses caching, the client browser does not even communicate with the server. So that endpoint doesn't get hit.
And what happens is that it loads the cached React app, and uses react routing, and because of it when the user clicks on the Sign in with Google button, and this route gets called:
Instead of communicating with the server, it uses react routing and the user gets redirected to the home page because of this:
<Redirect to="/home" />
I had to disable the PWA in order for the sign-in to work all the time. However, this had the side-effect of disabling caching and other PWA features like installation.
The solution is to prevent the use of caching when this route is called:
This is a similar question but it uses workbox which my app doesn't.
This is my serviceWorker file:
import axios from "axios";
const isLocalhost = Boolean(
window.location.hostname === "localhost" ||
window.location.hostname === "[::1]" ||
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
return;
}
window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
checkValidServiceWorker(swUrl, config);
} else {
console.log(
"Is not localhost. Just register service worker, calling registerValidSW"
);
registerValidSW(swUrl, config);
}
});
}
}
async function subscribeToPushNotifications(serviceWorkerReg) {
console.log("subscribeToPushNotifications is called");
let subscription = await serviceWorkerReg.pushManager.getSubscription();
if (subscription === null) {
const dev_public_vapid_key =
"BLhqVEcH5_0uDpSlwKfvNk7q5IwM5uxYf2w8qvHqdk0SrBpQMGKIZfBrlG-1XYvGxHZXHSik3pQ8IN8NeNCYRtU";
const prod_public_vapid_key =
"BBagXPEL91hwEird3KIG2WuxcWt0hOq1AA7QKtK1MlNqMxiBgQ_RCT8f7rCwYIkuHSVg65Xm68lIlGobXDT1yDI";
const public_vapid_key = isLocalhost
? dev_public_vapid_key
: prod_public_vapid_key;
subscription = await serviceWorkerReg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: public_vapid_key,
});
axios
.post("/api/push_notif_subscription/subscribe", subscription)
.then((response) => {})
.catch((error) => {
console.log(error);
});
}
}
function serviceWorkerRegistrationEnhancements(config, registration) {
registration.addEventListener("activate", function (event) {
event.waitUntil(() => {
if (config && config.onActivated) {
config.onActivated(registration);
}
});
});
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker.register(swUrl).then((registration) => {
console.log("Line right before calling subscribeToPushNotifications");
subscribeToPushNotifications(registration);
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (!installingWorker) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
serviceWorkerRegistrationEnhancements(config, registration);
registration.addEventListener("push", async function (event) {
const message = await event.data.json();
let { title, description, image } = message;
await event.waitUntil(showPushNotification(title, description, image));
});
});
}
export function showPushNotification(title, description, image) {
if (!("serviceWorker" in navigator)) {
console.log("Service Worker is not supported in this browser");
return;
}
navigator.serviceWorker.ready.then(function (registration) {
registration.showNotification(title, {
body: description,
icon: image,
actions: [
{
title: "Say hi",
action: "Say hi",
},
],
});
});
}
function checkValidServiceWorker(swUrl, config) {
fetch(swUrl, {
headers: { "Service-Worker": "script" },
}).then((response) => {
const contentType = response.headers.get("content-type");
if (
response.status === 404 ||
(!!contentType && contentType.indexOf("javascript") === -1)
) {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
console.log("Service worker found, calling registerValidSW");
registerValidSW(swUrl, config);
}
});
}
export function unregister() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister();
});
}
}
Upvotes: 3
Views: 1978