Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: CDN can serve one market's cached Store API response to another (#14781)
Damian Legawiecdfa050c39c98
diff --git a/docs/api-reference/store-api/localization.mdx b/docs/api-reference/store-api/localization.mdxindex 10c1c278ae..412c5197f6 100644--- a/docs/api-reference/store-api/localization.mdx+++ b/docs/api-reference/store-api/localization.mdx@@ -136,6 +136,16 @@ Each value is resolved in the following order:The locale and currency must be supported by the current store. If an unsupported value is provided, the API falls back to the store's default.</Note>+### Caching++Cacheable guest responses (products, categories, collections, markets, locales, currencies, policies, sellers) are sent with `Cache-Control: public` and:++```+Vary: Accept, X-Spree-Api-Key, Authorization, X-Spree-Country, X-Spree-Currency, X-Spree-Locale, X-Spree-Channel+```++A CDN or shared cache therefore stores one copy per country, currency, locale and channel, so a visitor in one market never receives another market's prices. The `country`, `currency` and `locale` query parameters are part of the URL, so they are cached separately without needing `Vary`. Responses to signed-in customers are `Cache-Control: private, no-store`.+## Translated ContentWhen a locale is set, all translatable fields are returned in the requested language. This includes product names, descriptions, category names, and other content managed through [translations](/developer/core-concepts/translations).diff --git a/docs/developer/core-concepts/pricing.mdx b/docs/developer/core-concepts/pricing.mdxindex a3cb202fca..77741c0ab3 100644--- a/docs/developer/core-concepts/pricing.mdx+++ b/docs/developer/core-concepts/pricing.mdx@@ -233,7 +233,7 @@ When resolving prices, Spree considers the full context of the request:The Store API automatically builds this context from the [request headers](/api-reference/store-api/localization) (`X-Spree-Currency`, `X-Spree-Country`) and authentication state. You don't need to construct it manually — just make API requests and the correct price is resolved.<Info>-Price resolution runs per request — there is no in-process caching of resolved prices. The Store API instead relies on HTTP/CDN caching, with `Vary` headers keyed on the `X-Spree-Currency` and `X-Spree-Locale` request headers so each currency/locale combination is cached separately at the edge.+Price resolution runs per request — there is no in-process caching of resolved prices. The Store API instead relies on HTTP/CDN caching, with `Vary` headers keyed on every request header that changes the price — `X-Spree-Country` (market), `X-Spree-Currency`, `X-Spree-Locale`, `X-Spree-Channel`, the publishable key and `Authorization` — so each combination is cached separately at the edge. See [HTTP caching](/developer/deployment/caching#http-caching-of-store-api-responses).</Info>## Time-Based Pricingdiff --git a/docs/developer/deployment/caching.mdx b/docs/developer/deployment/caching.mdxindex ef039ab3ec..77728a6a02 100644--- a/docs/developer/deployment/caching.mdx+++ b/docs/developer/deployment/caching.mdx@@ -23,6 +23,25 @@ config.cache_store = :redis_cache_store, { url: ENV["REDIS_URL"] }Works identically with Redis or Valkey (the Linux Foundation fork most hosting platforms now provision).+## HTTP caching of Store API responses++Read-only Store API endpoints (products, categories, collections, markets, locales, currencies, policies, sellers) are HTTP-cacheable for guests, so a CDN or reverse proxy in front of Spree can serve them from the edge:++- **Guests** get `Cache-Control: public, max-age=300` (list endpoints add `stale-while-revalidate=30`) plus an `ETag`, and conditional requests return `304 Not Modified`.+- **Signed-in customers** (a customer JWT in `Authorization`) get `Cache-Control: private, no-store` — nothing is cached.++Guest responses carry this `Vary` header:++```+Vary: Accept, X-Spree-Api-Key, Authorization, X-Spree-Country, X-Spree-Currency, X-Spree-Locale, X-Spree-Channel+```++Each of these headers changes the response body: the publishable key selects the store, `X-Spree-Country` selects the market (currency, prices, tax display, availability), and `X-Spree-Channel` controls price visibility and which products are listed. `Authorization` keeps a cached guest response from being served to a signed-in customer.++<Warning>+If your CDN ignores `Vary` or builds its own cache key (for example Cloudflare Cache Rules with a custom cache key), include every header listed above in that key, or it serves one market's or store's prices to another.+</Warning>+## Testing LocallyTo enable caching in the development environment:diff --git a/docs/developer/deployment/cdn.mdx b/docs/developer/deployment/cdn.mdxindex 4058962ded..5fa365f3cf 100644--- a/docs/developer/deployment/cdn.mdx+++ b/docs/developer/deployment/cdn.mdx@@ -6,6 +6,10 @@ description: >-To improve performance of your Spree application, we recommend using a CDN (Content Delivery Network) to cache images and static files.+<Note>+If you also cache Store API responses at the CDN, the cache key must include every header in the response's `Vary` header — see [HTTP caching of Store API responses](/developer/deployment/caching#http-caching-of-store-api-responses).+</Note>+We recommend using [Cloudflare](https://www.cloudflare.com/) as your CDN provider. It's free and simple to set up.After setting up your Cloudflare account and adding your domain name to Cloudflare, you will need to set your cache settings.diff --git a/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb b/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rbindex 95e1af1f5f..5e05f9f185 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb@@ -11,6 +11,33 @@ module Spreemodule HttpCachingextend ActiveSupport::Concern+ # Every request header that changes a publicly cacheable response.+ # A shared cache (CDN, reverse proxy) keys stored responses on these,+ # so a header missing here lets one visitor's response be served to+ # another:+ # - +Accept+ — response format+ # - +X-Spree-Api-Key+ — the publishable key selects the store (and+ # may bind a channel)+ # - +Authorization+ — a customer JWT turns the response private+ # (customer-group prices, gated catalog); without it a guest+ # response could be served to a signed-in customer+ # - +X-Spree-Country+ — selects the market (currency, prices, tax+ # display, availability)+ # - +X-Spree-Currency+ / +X-Spree-Locale+ — currency and language+ # - +X-Spree-Channel+ — price hiding + channel-scoped visibility+ #+ # Query-param equivalents (+?country=+, +?currency=+, +?locale=+)+ # are part of the URL and so already part of every cache key.+ VARY_HEADERS = %w[+ Accept+ X-Spree-Api-Key+ Authorization+ X-Spree-Country+ X-Spree-Currency+ X-Spree-Locale+ X-Spree-Channel+ ].freeze+included doafter_action :set_vary_headersend@@ -22,13 +49,11 @@ module Spreecurrent_user.nil?end- # Set Vary headers to ensure proper CDN caching by currency/locale/channel.- # X-Spree-Channel is included because the resolved channel changes the- # serialized body (price hiding + channel-scoped visibility), so a shared- # cache must not serve one channel's guest response to another channel.+ # Set Vary so a shared cache stores one guest response per+ # store/market/currency/locale/channel combination (see VARY_HEADERS).def set_vary_headersif guest_user?- response.headers['Vary'] = 'Accept, x-spree-currency, x-spree-locale, x-spree-channel'+ response.headers['Vary'] = VARY_HEADERS.join(', ')elseresponse.headers['Cache-Control'] = 'private, no-store'end@@ -70,12 +95,12 @@ module Spreeexpires_in expires_in, public: true- # Use Rails' stale? which handles ETag and Last-Modified. The channel- # is folded into the ETag so a shared cache never serves one channel's- # guest response to another; Last-Modified mirrors the resource's own- # timestamp as before.+ # Use Rails' stale? which handles ETag and Last-Modified. The request+ # context (currency, locale, market, channel) is folded into the ETag+ # so a revalidation never 304s across contexts; Last-Modified mirrors+ # the resource's own timestamp as before.stale?(- etag: [resource, cache_channel_fragment],+ etag: [resource, current_currency, current_locale, cache_market_fragment, cache_channel_fragment],last_modified: resource.try(:updated_at),public: true)@@ -84,7 +109,7 @@ module Spreeprivate# Build a cache key for a collection- # Includes: latest updated_at, total count, query params, pagination, expand, currency, locale, channel+ # Includes: latest updated_at, total count, query params, pagination, expand, currency, locale, market, channeldef collection_cache_key(collection)# For ActiveRecord collections use updated_at, for plain arrays use store's updated_at as proxylatest_updated_at = if collection.first&.respond_to?(:updated_at)@@ -103,12 +128,20 @@ module Spreeparams[:limit],current_currency,current_locale,+ cache_market_fragment,cache_channel_fragment]parts.compact.join('/')end+ # Identifies the resolved market (from X-Spree-Country / ?country=).+ # The market drives tax display and availability as well as currency,+ # so it is part of the guest cache identity.+ def cache_market_fragment+ Spree::Current.market&.id+ end+# Identifies the resolved channel for cache-key purposes. The channel# changes the serialized body (price hiding + channel-scoped visibility),# so it must be part of the guest cache identity. Uses the samediff --git a/spree/api/spec/controllers/concerns/spree/api/v3/http_caching_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/http_caching_spec.rbindex 2fbab14205..e83b79eb46 100644--- a/spree/api/spec/controllers/concerns/spree/api/v3/http_caching_spec.rb+++ b/spree/api/spec/controllers/concerns/spree/api/v3/http_caching_spec.rb@@ -19,7 +19,28 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller doit 'sets Vary header for CDN caching' doget :index- expect(response.headers['Vary']).to eq('Accept, x-spree-currency, x-spree-locale, x-spree-channel')+ expect(response.headers['Vary']).to eq(+ 'Accept, X-Spree-Api-Key, Authorization, X-Spree-Country, X-Spree-Currency, X-Spree-Locale, X-Spree-Channel'+ )+ end++ # Every header that changes the body must be in Vary, or a shared+ # cache serves one market's/store's/customer's response to another.+ %w[+ X-Spree-Country X-Spree-Currency X-Spree-Locale X-Spree-Channel X-Spree-Api-Key Authorization+ ].each do |header|+ it "varies on #{header}" do+ get :index++ vary = response.headers['Vary'].split(',').map { |h| h.strip.downcase }+ expect(vary).to include(header.downcase)+ end+ end++ it 'sets Vary on show responses too' do+ get :show, params: { id: product.prefixed_id }++ expect(response.headers['Vary']).to include('X-Spree-Country')endend@@ -138,6 +159,26 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller doexpect(eur_etag).not_to eq(original_etag)end+ # Two markets sharing a currency and locale — the market (tax display,+ # availability) is the only dimension that differs.+ context 'when the country resolves a different market' do+ let!(:germany) { create(:country, iso: 'DE', name: 'Germany') }+ let!(:de_market) do+ create(:market, store: store, currency: store.default_currency, default_locale: store.default_locale,+ tax_inclusive: true, countries: [germany])+ end++ it 'changes ETag when the resolved market changes' do+ get :index+ default_etag = response.headers['ETag']++ request.headers['x-spree-country'] = 'DE'+ get :index++ expect(response.headers['ETag']).not_to eq(default_etag)+ end+ end+# Publish the same products on both channels so the identical collection# is served either way — isolating the channel as the sole cache# dimension that differs (guards against a shared CDN cross-serving).