Dynamic Manifest with CRA

Nawaaz Kortiwala
2 min readOct 12, 2022

PWA or Progressive Web Apps offers us to install our web application into our device (mobile and desktop) just like a native application. It works on-top of a browser instance (depending on which browser we install the PWA from) and offers offline capabilities.

For a web app to be a PWA, it requires two things:

  1. service workersfor enabling the app to be used offline by storing and serving resources (static assets, API responses, etc.).
  2. manifest.json — a file that contains the operational and visual configuration for the PWA (background scripts, content scripts, and browser actions).

In this article, we will discuss about the manifest.json file and how to dynamically manipulate it for increased usability and a more customised user-experience.

Let’s start!

Here a basic example of a manifest.json file:

In regards to CRA, the manifest.json resides in the public folder and after the project is built (running yarn build or npm run build), the file gets copied into the build folder. From here, it is served directly like all the other static assets (images, javascript files, stylesheets, etc.) .

Now, given a situation where we need the manifest.json file to have a dynamic configuration, it’s really tricky to edit the default configurations. Let’s say that we need the start_url property — that tells the browser which path to load the PWA at, when opened — to be different for different user. For example, for user with an id=25, we need the start_url property to be:

“start_url”: “./?id=25”

For such a scenario, it’s nearly impossible to edit the contents of the manifest file — unless we have a custom server that handles serving of static assets and can edit the contents of the file on the go.

Solution

Generally, CRA appends the manifest.json file, automatically, in the index.html file using a link tag:

<link rel=”manifest” href=”%PUBLIC_URL%/manifest.json” />

And through here, the manifest.json file is request on load. Pretty basic.

Now, instead of requesting the manifest file over the network, we will append the content of the file directly to the href attribute.

We can use the React’s componentDidMount lifecycle method to append the manifest content.

First, we need to make changes in the above link tag in the index.html file (in the public folder) by removing the href tag and adding the id tag:

<link rel=”manifest” id=”dy-manifest” />

Then all we need to do is to add the content to the href attribute, with the manifest config, during the app load.

We can do something like this: use a wrapper component:

And use the wrapper as such:

And that’s it!

Similarly, we can changes/add/remove any other configuration attribute from the manifest.json file as needed.

Peace!

--

--