| 10 | // |
| 11 | // Max age is in seconds |
| 12 | function cacheControlFactory( |
| 13 | maxAge = 60 * 60, |
| 14 | { key = 'cache-control', public_ = true, immutable = false, maxAgeZero = false } = {} |
| 15 | ) { |
| 16 | const directives = [ |
| 17 | maxAge && public_ && 'public', |
| 18 | maxAge && `max-age=${maxAge}`, |
| 19 | maxAge && immutable && 'immutable', |
| 20 | !maxAge && 'private', |
| 21 | !maxAge && 'no-store', |
| 22 | maxAge >= 60 * 60 && `stale-while-revalidate=${60 * 60}`, |
| 23 | maxAge >= 60 * 60 && `stale-if-error=${24 * 60 * 60}`, |
| 24 | maxAgeZero && 'max-age=0', |
| 25 | ] |
| 26 | .filter(Boolean) |
| 27 | .join(', ') |
| 28 | return (res) => { |
| 29 | if (process.env.NODE_ENV !== 'production' && res.hasHeader('set-cookie')) { |
| 30 | console.warn( |
| 31 | "You can't set a >0 cache-control header AND set-cookie or else the CDN will never respect the cache-control." |
| 32 | ) |
| 33 | } |
| 34 | res.set(key, directives) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // These are roughly in order from shortest to longest |
| 39 | |