feat(images): enable Next.js image optimization with complete upstream buffer retrieval and explicit MIME types
This commit is contained in:
1 parent
89e59c8427
commit
08ad51152f
4 files changed
+81
-11
No files matched your search
@@ -32,6 +32,24 @@ function getCandidateUrls(filePath: string): string[] {
|
||||
return Array.from(set);
|
||||
}
|
||||
|
||||
function getMimeType(filePath: string, fallback: string): string {
|
||||
const ext = filePath.split('.').pop()?.toLowerCase();
|
||||
switch (ext) {
|
||||
case 'webp': return 'image/webp';
|
||||
case 'jpg':
|
||||
case 'jpeg': return 'image/jpeg';
|
||||
case 'png': return 'image/png';
|
||||
case 'gif': return 'image/gif';
|
||||
case 'svg': return 'image/svg+xml';
|
||||
case 'avif': return 'image/avif';
|
||||
case 'mp4': return 'video/mp4';
|
||||
case 'webm': return 'video/webm';
|
||||
case 'mp3': return 'audio/mpeg';
|
||||
case 'pdf': return 'application/pdf';
|
||||
default: return fallback || 'application/octet-stream';
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
@@ -42,9 +60,11 @@ export async function GET(
|
||||
return new NextResponse('Bad Request: Missing file path', { status: 400 });
|
||||
}
|
||||
|
||||
const rawFilePath = path.join('/');
|
||||
const filePath = path.map(segment => encodeURIComponent(segment)).join('/');
|
||||
const candidates = getCandidateUrls(filePath);
|
||||
|
||||
// Forward streaming/caching headers from client
|
||||
const forwardedHeaders: HeadersInit = {};
|
||||
const rangeHeader = request.headers.get('range');
|
||||
if (rangeHeader) forwardedHeaders['range'] = rangeHeader;
|
||||
@@ -68,7 +88,25 @@ export async function GET(
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// Continue
|
||||
// Continue trying next candidate
|
||||
}
|
||||
}
|
||||
|
||||
// If 304 received without body or if not found with conditional headers, retry unconditionally
|
||||
if (backendRes && backendRes.status === 304 && !backendRes.body) {
|
||||
for (const targetUrl of candidates) {
|
||||
try {
|
||||
const freshRes = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (freshRes.ok) {
|
||||
backendRes = freshRes;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// Continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +115,8 @@ export async function GET(
|
||||
}
|
||||
|
||||
const responseHeaders = new Headers();
|
||||
const contentType = backendRes.headers.get('content-type') || 'application/octet-stream';
|
||||
const rawContentType = backendRes.headers.get('content-type') || '';
|
||||
const contentType = getMimeType(rawFilePath, rawContentType);
|
||||
responseHeaders.set('Content-Type', contentType);
|
||||
|
||||
const contentLength = backendRes.headers.get('content-length');
|
||||
|
||||
Reference in new issue
Block a user