Skip to content

Commit c3c583b

Browse files
committed
feat: enhance image caching by implementing unique cache key generation for transformed images
1 parent 61df195 commit c3c583b

1 file changed

Lines changed: 16 additions & 3 deletions

File tree

src/app/api/image/route.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import fs from 'fs';
22
import path from 'path';
3+
import crypto from 'crypto';
34
import sharp from 'sharp';
45
import { NextRequest, NextResponse } from 'next/server';
56

@@ -66,9 +67,16 @@ export async function GET(request: NextRequest) {
6667
return NextResponse.json({ error: 'File not found' }, { status: 404 });
6768
}
6869

69-
// Stat the file for ETag / Last-Modified
70+
// Stat the file and build a cache key that is unique per source + transform params.
71+
// This prevents different image URLs from sharing the same cache validator.
7072
const stat = fs.statSync(filePath);
71-
const etag = `"${stat.size}-${stat.mtimeMs}"`;
73+
const cacheKey = [
74+
filePath,
75+
stat.size,
76+
stat.mtimeMs,
77+
searchParams.toString(),
78+
].join('|');
79+
const etag = `"${crypto.createHash('sha1').update(cacheKey).digest('hex')}"`;
7280
const lastModified = stat.mtime.toUTCString();
7381

7482
// Conditional request support
@@ -149,7 +157,12 @@ export async function GET(request: NextRequest) {
149157
const outputBuffer = await pipeline.toBuffer();
150158
const contentType = MIME[format] ?? 'image/webp';
151159

152-
return new NextResponse(outputBuffer.buffer as ArrayBuffer, {
160+
const responseBody = outputBuffer.buffer.slice(
161+
outputBuffer.byteOffset,
162+
outputBuffer.byteOffset + outputBuffer.byteLength,
163+
) as ArrayBuffer;
164+
165+
return new NextResponse(responseBody, {
153166
status: 200,
154167
headers: {
155168
'Content-Type': contentType,

0 commit comments

Comments
 (0)