Adding Rails API Caching with Service Workers

A PWA often interacts with a Rails API to fetch dynamic data. Efficient caching of API responses is key to delivering an offline experience.

1. Enabling Caching in Rails API

In Rails, enable server-side caching by configuring config/environments/production.rb:

config.action_controller.perform_caching = true
config.cache_store = :memory_store

For an API endpoint, use caching with expires_in:

class ArticlesController < ApplicationController
  def index
    articles = Rails.cache.fetch("articles", expires_in: 1.hour) do
      Article.all.to_json
    end
    render json: articles
  end
end

2. Caching API Responses in the Service Worker

Modify service_worker.js to cache API responses:

self.addEventListener("fetch", (event) => {
  if (event.request.url.includes("/api/articles")) {
    event.respondWith(
      caches.open("api-cache").then((cache) => {
        return fetch(event.request)
          .then((response) => {
            cache.put(event.request, response.clone());
            return response;
          })
          .catch(() => caches.match(event.request));
      })
    );
  }
});