2

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 2

1

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(
    ...          
));
}
Sign up to request clarification or add additional context in comments.

3 Comments

I did not know interceptors work for service workers(fetch requests) too, will give it a shot.
This won't work. CSP headers have to be set on the server before the responses ever make it to the client/Angular code.
@abraham Headers are being sent from the server but when these are cached and served from service workers those headers are not there.
0

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.

1 Comment

This. It's not Angular specific. Note that you probably also need worker-src, not connect-src, although in my case the error said the latter the fix was the former. See: developer.mozilla.org/en-US/docs/Web/HTTP/Headers/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.