The script resource is experiencing a redirect that is not permitted - Service Worker

I have integrated a Service Worker into my Angular application, and it works perfectly when running on localhost. However, when I attempt to deploy the code in a development or different environment, I encounter the following error:

Service worker registration failed: SecurityError: Failed to register a ServiceWorker for scope ('https://a.b.czoo.org/') with script ('https://a.b.czoo.org/sw.js'): 
The script resource is behind a redirect, which is disallowed.

Note: The URL mentioned () follows the root domain format, where 'a', 'b', and 'czoo' are placeholders. The actual deployment URL will be like 'https://a.b.czoo.org/AB-123', with AB-123 representing the branch name.

(Providing more context...)

The Service Worker file in my setup is written in TypeScript. During the build process, Webpack converts this file using `ts-loader` and `worker-loader`, placing it in the app's root folder as referenced in `src/app.component.ts`. For example,

app.component.ts

navigator.serviceWorker.register('/sw.js', { scope: '/' }).then(
  (): void => {
    console.log('Service worker registered');
  },
  (error): void => {
    console.error(`Service worker registration failed: ${error}`);
  },
);

This Service Worker file is imported through an `entry` option in the Webpack configuration (as done in the local environment).

webpack.config.js

entry: {
  vendor: config.vendor.packages,
  boot: './app/index.aot.ts',
  sw: './app/**/**/sw.ts',
},
module: {
  rules: [
    {
      test: /\.sw\.ts$/,
      use: [
        {
          // This generates a new sw.js file in the root, which is then referenced in app.component
          loader: 'worker-loader',
          options: {
            filename: "[name].js",
            publicPath: "/",
          },
        },
        {
          loader: 'ts-loader',
          options: {
            transpileOnly: true,
            happyPackMode: true,
          },
        },
      ],
    },
  ]
},

While the build process is successful, attempting to reach the development URL () results in the aforementioned error.

I have reviewed similar issues on Stack Overflow (SO Answer) and GitHub (GitHub Issue), but I was unable to pinpoint the root cause of the problem. I'm uncertain about how to effectively debug this issue.

I would greatly appreciate guidance on debugging this issue or any insights into the potential reasons behind it. Thank you.

Answer №1

Execute the following code

let result = await fetch("/sw.js", { redirect: "error" })
console.log(result)

To see where it is being redirected

Answer №2

Prior to initializing your worker, ensure that you send a request to the specified URL and handle the 302 response within a httpClient.get() function call. Then, utilize the updated response.url to direct to the post redirect URL required for your script.

this.httpClient.get('https://path_to_script/script.js', {
    observe: 'response'
  })
  .pipe(
    tap((response) => {
      // response.url is the new redirected url;
      navigator.serviceWorker.register(response.url as string, {
        scope: '/'
      }).then(
        () => {
          console.log('Service worker registered');
        },
        (error) => {
          console.error(`Service worker registration failed: ${error}`);
        }
      );
    }),
    catchError((e: any) => {
      console.log(e);
      return e;
    })
  ).subscribe((r) => { console.log(r); // have to subscribe otherwise client wont make request. });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Form with placeholders

Is there a way to personalize an email using different variables, like adding special characters such as $, {}, [] around the word to indicate it's a variable? For example, {name}. I'm looking for a plugin compatible with Angular 14+ that can ass ...

The process of unit testing a component to verify the presence of a specific component on the page

Presenting my straightforward custom component dubbed as NavbarComponent with the selector app-navbar. This component serves as a basic static navbar and is being displayed in app.component.html: app.component.html <app-navbar></app-navbar> &l ...

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...

Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service. This is the content of my component file: submitLoginForm() { if (this.loginForm.valid) { // send a http request to save t ...

Should the PHP interface be exported to a Typescript interface, or should it be vice versa?

As I delve into Typescript, I find myself coding backend in PHP for my current contract. In recent projects, I have created Typescript interfaces for the AJAX responses generated by my backend code. This ensures clarity for the frontend developer, whether ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Tips for linking my TypeScript document to the server

Recently diving into the world of Angular 2 and seeking to grasp its intricacies. Currently utilizing Visual Studio Code. How can I have the server monitor changes in the TypeScript file? Do I need a compiler to convert it to JavaScript for this purpose? ...

Passing data between two Angular directives using EventEmitter

Looking to share a variable between two directives in Angular 7 Check out the updated code here: https://stackblitz.com/edit/angular-ct49bn The issue arises when selecting a customer from the list, as the emitter fails to communicate with the other direc ...

Encountering an issue during Angular installation, which is resulting in an error message and preventing the

Whenever I attempt to install the Angular CLI using the command below: npm install -g @angular/cli An error message pops up, displaying: rollbackFailedOptional: verb npm-session 1a71d92fb103bc6 I'm puzzled as to why this issue is happening and ho ...

Introducing an extra 'pipe' in rxjs angular may result in generating errors

Encountering an unusual issue with Angular. The following code functions correctly: this.form.valueChanges .pipe( startWith(this.form.value), pairwise(), tap(() => console.log('aa')) ...

Is there a way to verify the presence of a service worker on a specific URL?

Is there a way for me to determine if external websites have a 'service-worker' or not? Here is what I think could work: Extract all the JavaScript files from the given URL Look for the string 'sw.js' (I am not entirely sure how to ...

I encountered an issue while generating a crypto address on the Waves blockchain using the @waves/waves-crypto library in TypeScript

Encountering an issue with finding "crypto-js" in "@waves/waves-crypto". Despite attempts to uninstall and reinstall the module via npm and importing it using "*wavesCrypto", the error persists within the module's index.d.ts file. I am attempting to ...

Storing data from a service into an array in Angular: Best practices

I have a service that provides getter and setter methods, returning id: number and title: String values from my dialog component. I am trying to save these responses into my data array but struggling to achieve it. For instance: 0: {id: 0, title: &qu ...

Enhance the MUI palette by incorporating TypeScript, allowing for seamless indexing through the palette

When utilizing the Material UI Palette with Typescript, I am encountering a significant issue due to limited documentation on MUI v5.0 in this area. Deep understanding of typescript is also required. The objective is to iterate through the palette and vir ...

Best practices for initializing model objects in a Redux or NgRx application architecture

Context: The development team is currently working on a sophisticated REST-based web application using Angular and the @ngrx library for managing state effectively. In order to represent entities retrieved from the server, such as accounts and users, we ...

What are the best scenarios for creating a constructor in Angular 2 using Typescript?

Check out these sample constructors I found in the Angular 2 documentation: export class AppComponent implements OnInit { title = 'Tour of heroes'; heroes: Hero[]; selectedHero: Hero; constructor(private heroService: HeroService ...

Please ensure that the property name is a valid type, such as 'string', 'number', 'symbol', or 'any'

Can anyone help me convert this JavaScript file to Typescript? import React, { useState } from 'react'; import { Button } from './Button'; import { Link } from 'react-router-dom'; import './Navbar.css'; import Settin ...

A guide on incorporating Google authentication into Vue.js with the use of TypeScript and the component-based syntax

Currently, I am in the process of integrating Google authentication into my Vue.js front end. The project was initialized using CLI with TypeScript and component style syntax enabled, alongside other configurations. Additionally, there is a backend web ser ...

What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below: class Sup { static member: any; static log() { console.log('sup'); } } If you write the following code: let x = Sup; Why does the type of x show up as typeof Sup (hig ...

The date in a nodejs application appears to be shifted by one day

Despite similar questions being asked before here, the solutions provided did not resolve my issue. Here is the scenario I am dealing with: https://i.sstatic.net/H9rcO.png Upon clicking save, I collect data from certain fields to generate a date using th ...