|
| 1 | +/** |
| 2 | + * Generic cache utilities for Netlify Edge Functions. |
| 3 | + * |
| 4 | + * This module provides a dual-layer caching strategy: |
| 5 | + * 1. Runtime Cache API (`caches.open()`) - Prevents edge function re-execution |
| 6 | + * for cached responses, reducing compute time and external API calls. |
| 7 | + * 2. Netlify CDN Cache - Enabled via Cache-Control headers in responses. |
| 8 | + * Netlify's CDN caches responses at the edge, reducing latency globally. |
| 9 | + * |
| 10 | + * According to Netlify Cache API docs (https://docs.netlify.com/build/caching/cache-api/): |
| 11 | + * - Use `caches.open(name)` to open a named cache instance |
| 12 | + * - Responses must have Cache-Control headers with max-age >= 1 second |
| 13 | + * - Only responses with status 200-299 can be cached |
| 14 | + * - Responses are automatically invalidated on site redeploy |
| 15 | + * - Cache operations must be within request handler scope |
| 16 | + * - Responses must be cloned before caching if used elsewhere |
| 17 | + * |
| 18 | + * According to Netlify caching overview (https://docs.netlify.com/build/caching/caching-overview/): |
| 19 | + * - Edge Functions are NOT cached by default |
| 20 | + * - Setting Cache-Control headers enables CDN caching |
| 21 | + * - Query parameters are automatically factored into cache keys |
| 22 | + * - Cache-Control max-age determines how long responses are cached |
| 23 | + * |
| 24 | + * The Cache API provides immediate cache hits within the same edge function execution, |
| 25 | + * while Netlify's CDN cache provides global distribution and reduces edge function |
| 26 | + * invocations across different edge locations. |
| 27 | + */ |
| 28 | + |
| 29 | +export interface CacheOptions { |
| 30 | + /** |
| 31 | + * Name of the cache instance to use. Defaults to 'default'. |
| 32 | + * Using a meaningful name helps organize cached responses. |
| 33 | + */ |
| 34 | + cacheName?: string; |
| 35 | + /** |
| 36 | + * Prefix for cache keys to avoid collisions. |
| 37 | + */ |
| 38 | + keyPrefix?: string; |
| 39 | + /** |
| 40 | + * Whether to add debug headers (X-Cache, X-Cache-Date). |
| 41 | + */ |
| 42 | + debugHeaders?: boolean; |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Normalizes a URL for consistent cache keys: |
| 47 | + * - Lowercases hostname |
| 48 | + * - Removes trailing slashes (except for root) |
| 49 | + * - Preserves path, query, and hash |
| 50 | + */ |
| 51 | +export function normalizeUrl(url: URL): string { |
| 52 | + const normalized = new URL(url); |
| 53 | + normalized.hostname = normalized.hostname.toLowerCase(); |
| 54 | + if (normalized.pathname !== '/' && normalized.pathname.endsWith('/')) { |
| 55 | + normalized.pathname = normalized.pathname.slice(0, -1); |
| 56 | + } |
| 57 | + return normalized.href; |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * Creates a cache key with optional prefix. |
| 62 | + */ |
| 63 | +export function createCacheKey(key: string, prefix?: string): string { |
| 64 | + return prefix ? `${prefix}${key}` : key; |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Retrieves a cached response if available. |
| 69 | + * Adds X-Cache: HIT header if debugHeaders is enabled. |
| 70 | + * |
| 71 | + * According to Netlify Cache API docs, cache operations must be within |
| 72 | + * the request handler scope. This function should be called from within |
| 73 | + * your edge function handler. |
| 74 | + * |
| 75 | + * @param cacheKey - The cache key to look up (can be a Request object or URL string) |
| 76 | + * @param options - Cache options |
| 77 | + * @returns Cached response or null if not found |
| 78 | + */ |
| 79 | +export async function getCachedResponse( |
| 80 | + cacheKey: string | Request, |
| 81 | + options: CacheOptions = {}, |
| 82 | +): Promise<Response | null> { |
| 83 | + const { cacheName = 'default', debugHeaders = true } = options; |
| 84 | + |
| 85 | + try { |
| 86 | + const cache = await caches.open(cacheName); |
| 87 | + const cachedResponse = await cache.match(cacheKey); |
| 88 | + if (cachedResponse) { |
| 89 | + if (debugHeaders) { |
| 90 | + // Add cache hit header for debugging |
| 91 | + const clonedResponse = cachedResponse.clone(); |
| 92 | + clonedResponse.headers.set('X-Cache', 'HIT'); |
| 93 | + return clonedResponse; |
| 94 | + } |
| 95 | + return cachedResponse; |
| 96 | + } |
| 97 | + } catch (error) { |
| 98 | + // Cache API might not be available in all environments |
| 99 | + console.warn('Cache API not available:', error); |
| 100 | + } |
| 101 | + return null; |
| 102 | +} |
| 103 | + |
| 104 | +/** |
| 105 | + * Stores a response in the cache. |
| 106 | + * Clones the response to avoid consuming the original body. |
| 107 | + * |
| 108 | + * According to Netlify Cache API docs: |
| 109 | + * - Only responses with status 200-299 can be cached |
| 110 | + * - Responses must have Cache-Control headers with max-age >= 1 second |
| 111 | + * - Cache operations must be within the request handler scope |
| 112 | + * - Responses are automatically invalidated on site redeploy |
| 113 | + * |
| 114 | + * @param cacheKey - The cache key to store under (can be a Request object or URL string) |
| 115 | + * @param response - The response to cache (must have status 200-299 and Cache-Control headers) |
| 116 | + * @param options - Cache options |
| 117 | + */ |
| 118 | +export async function storeInCache( |
| 119 | + cacheKey: string | Request, |
| 120 | + response: Response, |
| 121 | + options: CacheOptions = {}, |
| 122 | +): Promise<void> { |
| 123 | + const { cacheName = 'default' } = options; |
| 124 | + |
| 125 | + // Only cache successful responses (200-299 status codes) |
| 126 | + if (!response.ok || response.status < 200 || response.status >= 300) { |
| 127 | + return; |
| 128 | + } |
| 129 | + |
| 130 | + // Verify Cache-Control header exists with max-age >= 1 second |
| 131 | + const cacheControl = response.headers.get('Cache-Control'); |
| 132 | + if (!cacheControl || !cacheControl.includes('max-age=')) { |
| 133 | + console.warn('Response missing Cache-Control header with max-age, skipping cache'); |
| 134 | + return; |
| 135 | + } |
| 136 | + |
| 137 | + try { |
| 138 | + const cache = await caches.open(cacheName); |
| 139 | + // Clone response before caching since Response body can only be read once |
| 140 | + // The clone ensures the original response remains readable |
| 141 | + const responseToCache = response.clone(); |
| 142 | + await cache.put(cacheKey, responseToCache); |
| 143 | + } catch (error) { |
| 144 | + // Cache API might not be available in all environments |
| 145 | + console.warn('Failed to store in cache:', error); |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +/** |
| 150 | + * Wraps a response with cache miss headers if debugHeaders is enabled. |
| 151 | + */ |
| 152 | +export function markCacheMiss( |
| 153 | + response: Response, |
| 154 | + options: CacheOptions = {}, |
| 155 | +): Response { |
| 156 | + const { debugHeaders = true } = options; |
| 157 | + if (debugHeaders) { |
| 158 | + response.headers.set('X-Cache', 'MISS'); |
| 159 | + response.headers.set('X-Cache-Date', new Date().toISOString()); |
| 160 | + } |
| 161 | + return response; |
| 162 | +} |
| 163 | + |
| 164 | +/** |
| 165 | + * Wraps a response with cache date header if debugHeaders is enabled. |
| 166 | + */ |
| 167 | +export function addCacheDateHeader( |
| 168 | + response: Response, |
| 169 | + options: CacheOptions = {}, |
| 170 | +): Response { |
| 171 | + const { debugHeaders = true } = options; |
| 172 | + if (debugHeaders) { |
| 173 | + response.headers.set('X-Cache-Date', new Date().toISOString()); |
| 174 | + } |
| 175 | + return response; |
| 176 | +} |
0 commit comments