(props?: CacheHeaderMiddlewareProps)
| 53 | } |
| 54 | |
| 55 | export const cacheHeaderMiddleware = (props?: CacheHeaderMiddlewareProps) => { |
| 56 | return next => async req => { |
| 57 | const url = isServer ? props?.url : window.location.pathname |
| 58 | |
| 59 | const cacheControlHeader = (() => { |
| 60 | const foundRoute = findRoutesByPath({ path: url ?? "" })[0] |
| 61 | |
| 62 | // In a prefetch context, the custom TTL should come from the found route |
| 63 | // that is being prefetched, and not the current route. |
| 64 | // During a prefetch, the custom TTL of that found route, if any, is injected into |
| 65 | // the metadata. Thus, if metadata is present, we should use that TTL (even if undefined). |
| 66 | const ttl = req.cacheConfig.metadata |
| 67 | ? req.cacheConfig.metadata.maxAge |
| 68 | : foundRoute?.route?.serverCacheTTL |
| 69 | |
| 70 | switch (true) { |
| 71 | case shouldSkipCDNCache(req, props?.user, ttl, url): { |
| 72 | return { "Cache-Control": "no-cache" } |
| 73 | } |
| 74 | case !!ttl: { |
| 75 | return { |
| 76 | "Cache-Control": `max-age=${ttl}`, |
| 77 | } |
| 78 | } |
| 79 | default: { |
| 80 | return {} |
| 81 | } |
| 82 | } |
| 83 | })() |
| 84 | |
| 85 | req.fetchOpts.headers = { |
| 86 | ...req.fetchOpts.headers, |
| 87 | ...cacheControlHeader, |
| 88 | } |
| 89 | |
| 90 | const res = await next(req) |
| 91 | |
| 92 | return res |
| 93 | } |
| 94 | } |
no test coverage detected