Search code examples
reactjsservice-workercreate-react-app

Service worker unexpected behavior with 2 react apps on same domain


I have 2 react apps (bootstrapped with create-react-app) running on the same domain. One app is served on the root (mydomain.com) and the other is served inside a subfolder (mydomain.com/path). The bundles are served statically using nginx.

When I go to mydomain.com, the service worker for the root app is registered and on further visits loads the index.html from the cache. When I visit mydomain.com/path/ the service worker for the second app is registered and on further visits loads the appropriate index.html from the cache.

The issue is that when I visit mydomain.com/path (without a trailing slash), the service worker for the app on the root loads its index.html, and basically overrides the service worker registered for the subfolder (/path). However, it works fine if I visit mydomain.com/path/ (with a trailing slash), and the service worker for the subfolder takes charge.

I am not sure if that is the expected behavior of the service worker. If yes, how can I get it to work without having to use a trailing slash? (I already tried explicitly setting a scope while registering the service worker for the subfolder)


Solution

  • I'm afraid this is an edge case that current browsers don't handle well.

    However it's not difficult to modify the service-worker on the root path so that it is active only if the path is not /path.

    if( !self.location.pathname.startsWith('/path') ) {
        // Do root service-worker stuff
    }