Skip to content

Commit fa7be78

Browse files
authored
Merge pull request #69 from craftcms/feature/stale-while-revalidate
Add stale-while-revalidate to default responses
2 parents db67c76 + 1401403 commit fa7be78

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

src/Config.php

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class Config extends BaseConfig
3333
public ?string $previewDomain = null;
3434
public bool $useQueue = true;
3535
public int $staticCacheDuration = DateTimeHelper::SECONDS_YEAR;
36+
public int $staleWhileRevalidateDuration = DateTimeHelper::SECONDS_HOUR;
3637
public ?string $storageEndpoint = null;
3738
public bool $useAssetCdn = true;
3839
public bool $useArtifactCdn = true;

src/StaticCache.php

+19-8
Original file line numberDiff line numberDiff line change
@@ -222,17 +222,28 @@ private function addCacheHeadersToWebResponse(): void
222222
$this->cacheDuration = $this->cacheDuration ?? Module::getInstance()->getConfig()->staticCacheDuration;
223223
$headers = Craft::$app->getResponse()->getHeaders();
224224

225-
$cacheControl = Craft::$app->getResponse()->getHeaders()->get(
226-
HeaderEnum::CACHE_CONTROL->value
227-
);
228-
229-
// Copy the cache-control header to the cdn-cache-control header
230-
Craft::$app->getResponse()->getHeaders()->setDefault(
225+
$cacheControlDirectives = Collection::make($headers->get(
226+
HeaderEnum::CACHE_CONTROL->value,
227+
first: false,
228+
));
229+
230+
// Copy cache-control directives to the cdn-cache-control header
231+
// @see https://developers.cloudflare.com/cache/concepts/cdn-cache-control/#header-precedence
232+
$staleWhileRevalidateDuration = Module::getInstance()->getConfig()->staleWhileRevalidateDuration;
233+
$cdnCacheControlDirectives = $cacheControlDirectives->isEmpty()
234+
? Collection::make([
235+
'public',
236+
"max-age=$this->cacheDuration",
237+
"stale-while-revalidate=$staleWhileRevalidateDuration",
238+
])
239+
: $cacheControlDirectives;
240+
241+
$headers->setDefault(
231242
HeaderEnum::CDN_CACHE_CONTROL->value,
232-
$cacheControl ?? "public, max-age=$this->cacheDuration",
243+
$cdnCacheControlDirectives->implode(','),
233244
);
234245

235-
// Capture, remove any existing headers so we can prepare them
246+
// Capture, remove any existing headers, so we can prepare them
236247
$existingTagsFromHeader = Collection::make($headers->get(HeaderEnum::CACHE_TAG->value, first: false) ?? []);
237248
$headers->remove(HeaderEnum::CACHE_TAG->value);
238249
$this->tags = $this->tags->push(...$existingTagsFromHeader);

0 commit comments

Comments
 (0)