Is it possible to create an npm library that uses service workers without requiring end-user script configuration?

The Problem

I want to create an npm library that uses service workers under the hood, where the end user does not need to configure anything—ideally, not even place or reference a sw.js file.

The main challenge I’m facing is that navigator.serviceWorker.register('somePath') requires the somePath to be relative to the final HTML file where the code is executed. This depends on the framework being used, for example:

  • In Next.js, service workers need to be placed in the public/ folder.
  • In Vite, they belong in the project’s root directory.

Since my library lives in node_modules, I don’t have control over these paths.

What I’d like:

  1. Zero setup: by simply running a function, the library takes care of everything else, including registering service workers. The user does not need to configure any path or add files to any specific location in their project.
  2. Fallback option (if zero setup isn’t possible): Provide a simplified setup process to reduce user effort. For example, I considered using type: 'module' during registration:
navigator.serviceWorker.register('somePath', {
  scope: '/',
  type: 'module',
});

Then my idea was for the user to import the library’s service worker script in their framework-specific file (e.g., public/sw.js in Next.js):

// public/sw.js for Next.js or sw.js for Vite
import { serviceWorkerScript } from 'myLibrary';

serviceWorkerScript();

But even this approach has issues. The import path must be relative to the script and does not support libraries installed in node_modules. So that code will throw an error.

I have also found that bypassing the restriction of placing the script in a separate file (e.g. with a string or Blob) is not a valid option.[ 1 ][ 2 ]

My question:

  1. Is it possible to achieve a zero-setup solution where the service worker script is registered and functional without requiring user intervention?
  2. If not, what’s the simplest way to guide users in configuring the service worker, minimizing complexity and effort?

I’m open to alternative approaches or best practices to handle this scenario efficiently. Any help is appreciated!