> For the complete documentation index, see [llms.txt](https://pwa.spomky-labs.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pwa.spomky-labs.com/1.4.x/the-service-worker/workbox/custom-cache-strategy.md).

# Custom Cache Strategy

Custom cache strategies allow you to programmatically define Workbox caching rules beyond the standard configuration options. This provides maximum flexibility for complex caching scenarios.

## Overview

While the PWA Bundle provides convenient configuration options for common caching patterns (asset caching, image caching, etc.), some applications require custom caching logic that goes beyond standard configuration. The bundle supports programmatic cache strategy creation through the `WorkboxCacheStrategy` class.

## When to Use Custom Cache Strategies

Use custom cache strategies when you need to:

1. **Dynamic route matching** - Cache routes based on complex logic
2. **Custom plugins** - Apply specialized Workbox plugins (ExpirationPlugin, BackgroundSyncPlugin, etc.)
3. **Per-route configuration** - Different strategies for different URL patterns
4. **Advanced caching logic** - Multi-tenant applications, authenticated APIs, conditional caching
5. **Runtime flexibility** - Strategies that change based on application state

## Quick Example

{% code title="src/ServiceWorker/CacheStrategy/ApiCacheStrategy.php" lineNumbers="true" %}

```php
<?php

namespace App\ServiceWorker\CacheStrategy;

use SpomkyLabs\PwaBundle\CachingStrategy\WorkboxCacheStrategy;
use SpomkyLabs\PwaBundle\WorkboxPlugin\ExpirationPlugin;
use Symfony\Component\DependencyInjection\Attribute\AsTaggedItem;

#[AsTaggedItem('spomky_labs_pwa.cache_strategy')]
final readonly class ApiCacheStrategy extends WorkboxCacheStrategy
{
    public static function create(): self
    {
        return WorkboxCacheStrategy::create(
            enabled: true,
            requireWorkbox: true,
            strategy: CacheStrategyInterface::STRATEGY_NETWORK_FIRST,
            matchCallback: '({url}) => url.pathname.startsWith("/api/")',
        )
            ->withName('api-cache')
            ->withPlugin(
                ExpirationPlugin::create(
                    maxEntries: 50,
                    maxAgeSeconds: 3600,
                )
            );
    }
}
```

{% endcode %}

This creates a cache strategy that:

* Uses NetworkFirst strategy for all `/api/` routes
* Limits the cache to 50 entries
* Expires cached responses after 1 hour

## Complete Documentation

For comprehensive documentation on creating custom cache strategies, including:

* **WorkboxCacheStrategy API** - Complete method reference
* **All Workbox Plugins** - ExpirationPlugin, BackgroundSyncPlugin, CacheableResponsePlugin, etc.
* **Strategy Types** - CacheFirst, NetworkFirst, StaleWhileRevalidate, NetworkOnly, CacheOnly
* **Real-World Examples** - Multi-tenant apps, authenticated APIs, conditional caching
* **Advanced Patterns** - Per-user caching, geo-based caching, A/B testing
* **Testing & Debugging** - Service worker inspection, cache verification

See the complete [**Custom Cache Strategies**](/1.4.x/the-service-worker/custom-cache-strategies.md) documentation.

## Standard Workbox Configuration

For most applications, the standard Workbox configuration options are sufficient:

* [**Asset Caching**](/1.4.x/the-service-worker/workbox/asset-caching.md) - Cache CSS, JavaScript, and static assets
* [**Image Caching**](/1.4.x/the-service-worker/workbox/image-caching.md) - Optimize image caching with size/age limits
* [**Font Caching**](/1.4.x/the-service-worker/workbox/font-caching.md) - Cache web fonts for offline use
* [**Background Sync**](/1.4.x/the-service-worker/workbox/backgoundsync.md) - Retry failed requests in the background
* [**Offline Fallback**](https://github.com/Spomky-Labs/phpwa-doc/blob/1.4/the-service-worker/workbox/offline-fallbacks.md) - Provide fallback pages when offline

## Related Documentation

* [**Custom Cache Strategies**](/1.4.x/the-service-worker/custom-cache-strategies.md) - Complete programmatic cache strategy guide
* [**Workbox Configuration**](/1.4.x/the-service-worker/workbox.md) - Overview of all Workbox options
* [**Service Worker Configuration**](/1.4.x/the-service-worker/configuration.md) - Service worker setup

## Resources

* **Workbox Strategies**: <https://developer.chrome.com/docs/workbox/modules/workbox-strategies/>
* **Workbox Plugins**: <https://developer.chrome.com/docs/workbox/reference/workbox-core/>
* **Workbox Routing**: <https://developer.chrome.com/docs/workbox/modules/workbox-routing/>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://pwa.spomky-labs.com/1.4.x/the-service-worker/workbox/custom-cache-strategy.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
