Manage image caching

Commerce images can be cached by the browser and the content delivery network (CDN) by default. Caching is desirable for performance reasons, but you must ensure that it does not lead to out-of-date images displaying on your pages.

On a production site, calls to Commerce endpoints that refer to images, such as product, SKU, and collection endpoints, respond with image URLs that include a sequence of numbers. For example:

/file/v7875483805069966233/products/APP_WeekendTrouser_full.jpg

In this example, v7875483805069966233 is a checksum of the file. Commerce updates this value automatically when the image is changed and published. The checksum ensures that an earlier version of the image that has been cached in the browser or CDN is not displayed.

If you generate your own image URLs (for example, if you use images that are not explicitly associated with products, SKUs, or collections), then when you modify an image, its URL typically does not change. As a result, an out-of-date cached version of the image may continue to be displayed. Similarly, if you reuse an existing image URL for a new image, the old image may be displayed instead.

To prevent these issues, you should use a cache-busting strategy to ensure only up-to-date images are displayed. For example, the URLs you generate could incorporate a timestamp that gets updated each time the image is updated. You can implement this by using the lastpublishtimestamp value from the ccRestClient module. Each time an image loaded with this parameter is modified and published, the value of the parameter changes, ensuring that previously cached versions are not displayed. Alternatively, you can get the full pathname for an image, including the checksum value, by calling the getFileURLs endpoint in the Store API. For example:

PUT /ccstore/v1/files/urlMappings  HTTP/1.1

{
  "filePaths": [
    "/products/cat5cable_LARGE.jpg"
  ]
}
The response includes the complete pathname, including the current checksum value:
{
    "/products/cat5cable_LARGE.jpg": "http://myserver.example.com:7002/file/v2441433713947926995/products/cat5cable_LARGE.jpg",
    "links": [
        {
            "rel": "self",
            "href": "http://myserver.example.com:7002/ccstore/v1/files/urlMappings"
        }
    ]
}