Adding headers to angular service worker responses

Viewed 1202

Some of the responses from service workers are violating the CSP, and I may need to add this header:

Content-Security-Policy = "connect-src *;"

to all the responses from service workers as explained here and here.

How can I add response headers to service worker responses using angular PWA?

2 Answers

You can use http interceptors for intercepting any kind of http request & response in one place. It is also applicable for service workers.

Please find a detailed explanation here.

https://angular.io/api/common/http/HttpInterceptor

Example:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
    ...          
));
}

The response headers need not be set on the cached response returned by the service worker, instead the solution is to set special CSP headers on the server to the response for the SW script. I.e., when the browsers requests ngsw-worker.js (the default name for the Angular SW script), the server should attach special CSP headers (e.g. Content-Security-Policy: connect-src *) to that response.

Related