#13: Hosting PWA on Static Web Apps

Welcome to Week 2, Day 6 of #30DaysOfSWA!!

Yesterday we talked about deploying Blazor apps on Static Internet Apps. Let’s proceed at this time with yet another sort of the tasks you possibly can efficiently host on SWA – Progressive Internet Apps (PWAs).

What We’ll Cowl

Concerning the Writer

Maxim Salnikov works on the Developer Relations staff in Norway, based #PWASummit #ngVikingsConf and #mobileeraconf, and is a Google Developer Knowledgeable on Internet Applied sciences. He speaks often on Progressive Internet Apps (PWA) and Angular. Observe him @webmaxru or right here on style-tricks.com

Progressive Internet Purposes

A Progressive Internet App (PWA) is an online frontend software that’s progressively enhanced utilizing open net applied sciences, to verify it delivers the very best expertise on each gadget, primarily based on obtainable capabilities. The “baseline” to your app to have a title “progressive” is its installability and offline-readiness. We skip the “served with https” requirement as a result of it grew to become a baseline for any net app as of late.

#30DaysOfPWA - Core Concepts

This chapter of #30DaysOfSWA assumes that you’re conversant in the fundamental ideas of a Service Employee API and automating your service employee with the Workbox library. In the event you want to find out about these applied sciences, you might be welcome to undergo the Core Ideas a part of the #30DaysOfPWA undertaking to find out about PWA fundamentals – see the roadmap above, or compensate for that collection right here on style-tricks.com:

I additionally advocate the video under on Automating a service employee with Workbox 6 for a quickstart introduction to Workbox.

Is internet hosting a PWA on Azure Static Internet Apps totally different from “basic” apps?

A Progressive Internet Software continues to be an online frontend app so the preliminary scaffolding of your SWA useful resource is similar – you could have realized learn how to deploy and configure varied forms of net apps from the earlier chapters of the #30DaysOfSWA. However to make it possible for your “PWA on SWA” works as supposed each on-line & offline to supply the very best consumer & developer experiences, you would possibly must pay particular consideration to some implementation particulars and fine-tune some configuration choices. We’ll undergo the next factors on this chapter:

  • Constructing your service employee as part of the general app construct
  • Organising HTML5 routing – for the Single-Web page Software (SPA) use-case
  • Making use of caching methods for SWA-hosted APIs
  • Displaying customized error pages
  • How one can take care of authentication in PWA

Pattern undertaking

I created a PWA on SWA Starter undertaking with all one of the best practices applied. The app is hosted on SWA as proven under. Let’s discover it!

PWA Starter on SWA

Technical stack:

  • A React software scaffolded by the create-react-app instrument. A easy SPA with a couple of routes and the chance to name API endpoints. Notice that the approaches described are relevant for any net frontend software: framework-based (together with your customized frameworks) or “vanilla” JavaScript. We use React just for getting nearer to the real-world situation of the fashionable frontend app growth when you need to carry out some operations together with your supply code (“construct the app”) earlier than the deployment.
  • A service worker powered by the Workbox library.
  • Two API endpoints created inside SWA useful resource – to emulate “dynamic” (/api/information) and “conservative” (/api/archives) information sources.

Constructing your service employee as part of the general app construct

The service employee file we’ve got within the src/sw folder of the applying isn’t prepared for the deployment. We have now to

  1. Process it by the workbox-build module to populate with the sources to precache (to supply offline-readiness)
  2. Bundle it
  3. Select manufacturing or growth mode
  4. Minify for deployment

Because of this in package deal.json‘s scripts we’ve got "build-sw": "node scripts/sw-build.js && npx rollup -c" command that’s constructing a service employee file and copies it into the app distribution folder.

By default, Azure Static Internet Apps runs npm run construct command to construct your software. So don’t forget so as to add a service employee construct command there. The ensuing command will likely be:

"construct": "react-scripts construct && npm run build-sw"
Enter fullscreen mode

Exit fullscreen mode

As an alternative of react-scripts construct, there could be a command to construct an software utilizing a framework/bundler of your selection. Vital: Maintain this order – you all the time construct a service employee after the primary software as a result of the distribution folder will likely be scanned to checklist the information to precache primarily based on the pattern you offered.

Organising HTML5 routing – for the Single-Web page Software (SPA)

For having right navigation in your single-page software, you need to “ask” the webserver to redirect all navigation requests to index.html – to run the applying and let it do the routing. In SWA, you need to have one thing like this within the configuration file:

"navigationFallback": {
  "rewrite": "index.html",
  "exclude": ["/images/*.{png,jpg,gif}", "/static/*"]
Enter fullscreen mode

Exit fullscreen mode

Greatest practices:

  • At all times “exclude” as a lot as potential in navigationFallback – it can assist you to to determine and repair “useful resource not discovered” errors.
  • Don’t copy staticwebapp.config.json to the app distribution folder – SWA will discover it in any location inside the app supply code.

In case of PWA, there’s an additional layer of this fallback: the primary in a row to deal with navigation requests is a service employee. Within the service-worker.js we’ve got to have the next block for proper routing in SPAs:

const navHandler = createHandlerBoundToURL('/index.html');
const navigationRoute = new NavigationRoute(navHandler, {
  denylist: [
    new RegExp('^/images/'),
    new RegExp('^/static/'),
Enter fullscreen mode

Exit fullscreen mode

The above configuration will work wonderful for opening each root url and “deep hyperlinks” like /about each in on-line and offline modes.

Displaying customized error pages

It is a finest follow to create and present customized error pages (for instance for 404 Not Discovered) as an alternative of those built-in within the browsers. And it is sensible to maintain these pages so simple as potential – with out operating a SPA itself. To arrange customized error pages, you add the next block to the SWA config

"responseOverrides": {
  "400": {
    "rewrite": "/400.html"
  "404": {
    "rewrite": "https://style-tricks.com/404.html"
Enter fullscreen mode

Exit fullscreen mode

These pages will likely be excluded from SWA’s navigation fallback robotically as a result of these two html are within the app distribution folder. However for the Workbox and specific directive wanted – simply add these addresses to the identical denylist we met with the HTML5 navigation part.

Making use of caching methods for SWA-hosted APIs

With Workbox, runtime caching is easy: you specify a url sample to “hear” and intercept, and a caching technique to use. There are 5 strategies obtainable and you may all the time create a customized one. By default, all API urls begin with /api. Then in a service worker, we’ll add this block for caching responses from our two API endpoints utilizing totally different methods:

  ({ url }) => url.pathname.startsWith('/api/information'),
  new NetworkFirst()

  ({ url }) => url.pathname.startsWith('/api/archives'),
  new CacheFirst()
Enter fullscreen mode

Exit fullscreen mode

Now, the info from APIs, as soon as fetched, can be obtainable offline!

Mini-exercise: Open the hosted PWA on SWA Starter, open the Community tab of DevTools, and click on on two buttons within the “API caching” demo space. What distinction do you see within the community request/response patterns for these two methods?

How one can take care of authentication in PWA

A few vital guidelines right here:

  1. Explicitly exclude the .auth system folder of SWA from Workbox’s navigation fallback (use denylist) and by no means arrange runtime caching for it
  2. By no means runtime-cache all information customers fetch from restricted API endpoints (served by SWA or exterior)

And it is a finest follow to by no means precache and all the time exclude from the service employee’s navigation fallback all urls associated to the consumer authentication and restricted elements of your software. Have a look on the ensuing denylist of our pattern software.

Train: Deploy your PWA on SWA, run offline, and set up it!

Hopefully, you are able to attempt one thing enjoyable that can reinforce what you realized at this time.

For this train:

  • Fork the PWA on SWA Starter repository and deploy it to Azure Static Internet Apps utilizing the abilities you gained within the earlier chapters of the #30DaysOfSWA
  • Open the url you obtained after the SWA useful resource was created
  • Now, go offline (disconnect from the Web or emulate offline mode within the DevTools) and reload the web page – it nonetheless works!
  • Utilizing the “App obtainable” icon on the right-hand aspect of the desktop browser’s deal with bar, set up the applying in your laptop computer – now it behaves like a local one!


Listed here are some sources to get you began together with your Progressive Internet App journey into

Add a Comment

Your email address will not be published. Required fields are marked *