Very recently I ran into an issue trying to get my site working while using Create-React-App 4’s included service-worker and registering it to create a PWA. The site worked before registering, but after registering the service-worker, clicking on login just brought me to a blank screen. While searching I found a similar issue reported with Vue, but not for CRA, so I thought I would share in case anyone else is similarly confused.
Background
The login uses Netlify functions to connect to the Spotify Web API. There’s a login function that redirects to the Spotify login page, and a callback function that receives the access and refresh tokens and then redirects to the web-app proper.
Issue
Registering the service worker will result in no return from Netlify function endpoints. This makes logging in impossible.
Resolution
Modify the service-worker.js to exclude Netlify function endpoints from the routing. Find this section of code in the default CRA 4 service-worker.js
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }) => {
// If this isn't a navigation, skip.
if (request.mode !== "navigate") {
return false;
} // If this is a URL that starts with /_, skip.
if (url.pathname.startsWith("/_")) {
return false;
} // If this looks like a URL for a resource, because it contains // a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
} // Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + "/index.html")
);
Add a condition to exclude the Netlify function endpoints before the return statement.
// If this is a URL for a serverless function, skip
if (url.pathname.startsWith("/.netlify/functions")) {
return false;
}
That’s it. It should work. In my case, I only use the serverless functions for authentication to the Spotify Web API (login, callback, and refresh_token), so it’s not something I want the service-worker handling anyway.
Simple enough, but it wasn’t obvious to me at first. Open to hearing if there are any potential pitfalls with this approach, as I haven’t found any recommended resolutions for this.