From 82b9d252aa4af69df5f1914f385de8530c041212 Mon Sep 17 00:00:00 2001 From: Andres Date: Thu, 12 Jun 2025 22:44:51 +0200 Subject: [PATCH] image optimizations --- image-loader.js | 18 ++++++++++++++++++ next.config.mjs | 12 ++++++++++++ 2 files changed, 30 insertions(+) diff --git a/image-loader.js b/image-loader.js index 002dad2..2caf41a 100644 --- a/image-loader.js +++ b/image-loader.js @@ -1,6 +1,13 @@ //@ts-nocheck const cdnUrl = 'https://balatromp.b-cdn.net' +// For production builds, we use a deterministic buildId based on the build time +// This ensures all images in a single build use the same cache key +// In development, we use a random value to prevent caching during development +const buildId = process.env.NODE_ENV === 'production' + ? process.env.BUILD_ID || process.env.VERCEL_GIT_COMMIT_SHA || Date.now().toString() + : Date.now().toString() + Math.random().toString(36).substring(2, 15); + export default function bunnyLoader({ src, width, quality }) { if (!cdnUrl) { throw new Error('missing NEXT_PUBLIC_CDN_URL env variable.') @@ -8,5 +15,16 @@ export default function bunnyLoader({ src, width, quality }) { const params = new URLSearchParams() params.set('width', width.toString()) params.set('quality', (quality || 100).toString()) + + // Add buildId as a query parameter for cache invalidation + // This ensures each new build will have different URLs, forcing the CDN to fetch fresh content + params.set('v', buildId) + + // For BunnyCDN, we can add a cache-control hint + // This tells the CDN to cache the image for a long time (1 year) + // Since we have the version parameter, we can safely cache for a long time + params.set('maxage', '31536000') // 1 year in seconds + + // Return the URL with cache parameters return `${cdnUrl}${src}?${params.toString()}` } diff --git a/next.config.mjs b/next.config.mjs index 84760ba..36de8ef 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -13,6 +13,18 @@ const config = { images: { loader: 'custom', loaderFile: './image-loader.js', + // Set minimumCacheTTL to a high value to ensure Next.js doesn't invalidate the cache too early + minimumCacheTTL: 60 * 60 * 24 * 365, // 1 year in seconds + }, + // Generate a unique build ID for each build if not provided by the environment + // This will be used for cache invalidation in the image loader + generateBuildId: async () => { + // Use existing build ID if available (e.g., from CI/CD) + if (process.env.BUILD_ID) { + return process.env.BUILD_ID + } + // Otherwise, use a timestamp + return `build-${Date.now()}` }, } const withNextIntl = createNextIntlPlugin()