Search code examples
.htaccesscachingprogressive-web-appsservice-workerauto-update

How to handle Cache in .htaccess file when using a Service Worker


I'm coding a PWA for the first time and wonder if my .htaccess cache policy isn't about to conflict with my Service Worker Stategies. Here is how it looks in my .htaccess file

<IfModule mod_expires.c>

    ExpiresActive on

    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"

    ExpiresByType text/css "access plus 1 days"
</IfModule>

Should I remove that part in order to make my Service Worker handle cache properly ?


Solution

  • Thea meaning of "conflict" is not very clear here. It depends completely on what you mean by that. With 99.99 % certainty there's no "conflict" of any kind, these are inherently separate technologies that don't step on each others' toes. Be aware that Service Worker is a scriptable interface so there's no single Service Worker. Your SW could do something completely different than mine.

    It is good to remember that caches work like this:

    Without Service Worker: Browser <--> Browser's HTTP cache (HTTP headers) <--> HTTP Server

    With Service Worker: Browser <--> Service Worker <--> Browser's HTTP cache (HTTP headers) <--> HTTP Server

    Now, in your case, the .htaccess is the thing that attaches HTTP caching headers to the responses served by your HTTP server. So those caching headers will be seen by the Service Worker when it contacts the HTTP server. They're not "conflicting". They're not an "either/or" type of a situation. They're doing different things.

    Example:

    1. Server has app.css
    2. Browser asks for app.css
    3. Service Worker sees the request for app.css
    4. Service Worker sends the request to the HTTP server
    5. Request goes through browser's HTTP interface and cache
    6. HTTP server responds with app.css and says: "Cache this for one month!"
    7. Response comes back through browser's HTTP interface and is saved in the HTTP cache
    8. Service Worker maybe does something with the response
    9. Service Worker forwards the response back to the browser
    10. Browser now has app.css

    Point 8: at this point usually the SW caches the response in the Cache API (this is separate, not HTTP cache). Point 3: at this point usually the SW checks the Cache API to see whether the request has already been cached (if above has happened). If Cache API provides the answer, SW skips steps 4–8 and just responds with the cached version.

    But, because the Serwice Worker is scriptable, it might be doing something different.

    I REALLY RECOMMEND you read this blog post about different HTTP caching schemes and how they work with Service Worker: https://jakearchibald.com/2016/caching-best-practices/