feat(media): implement nextjs media proxy API routes (/api/uploads & /api/media) with server-side caching and streaming
This commit is contained in:
1 parent
d9c693c41b
commit
fa1a35c835
19 files changed
+13806
-13030
No files matched your search
@@ -0,0 +1,132 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
) {
|
||||
try {
|
||||
const { path } = await params;
|
||||
if (!path || path.length === 0) {
|
||||
return new NextResponse('Bad Request: Missing file path', { status: 400 });
|
||||
}
|
||||
|
||||
const filePath = path.map(segment => encodeURIComponent(segment)).join('/');
|
||||
const backendBase = (
|
||||
process.env.INTERNAL_API_URL ||
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
'http://127.0.0.1:4001'
|
||||
).replace(/\/api\/?$/, '');
|
||||
|
||||
const targetUrl = `${backendBase}/uploads/${filePath}`;
|
||||
|
||||
// Forward streaming/caching headers from client to backend
|
||||
const forwardedHeaders: HeadersInit = {};
|
||||
const rangeHeader = request.headers.get('range');
|
||||
if (rangeHeader) {
|
||||
forwardedHeaders['range'] = rangeHeader;
|
||||
}
|
||||
const ifNoneMatch = request.headers.get('if-none-match');
|
||||
if (ifNoneMatch) {
|
||||
forwardedHeaders['if-none-match'] = ifNoneMatch;
|
||||
}
|
||||
const ifModifiedSince = request.headers.get('if-modified-since');
|
||||
if (ifModifiedSince) {
|
||||
forwardedHeaders['if-modified-since'] = ifModifiedSince;
|
||||
}
|
||||
|
||||
const backendRes = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: forwardedHeaders,
|
||||
cache: 'no-store', // Always stream directly or use Next.js response headers
|
||||
});
|
||||
|
||||
if (!backendRes.ok && backendRes.status !== 304 && backendRes.status !== 206) {
|
||||
return new NextResponse(`Media not found or error from upstream (${backendRes.status})`, {
|
||||
status: backendRes.status,
|
||||
});
|
||||
}
|
||||
|
||||
// Build response headers with long-term caching and media streaming support
|
||||
const responseHeaders = new Headers();
|
||||
|
||||
// Forward essential media headers
|
||||
const contentType = backendRes.headers.get('content-type') || 'application/octet-stream';
|
||||
responseHeaders.set('Content-Type', contentType);
|
||||
|
||||
const contentLength = backendRes.headers.get('content-length');
|
||||
if (contentLength) {
|
||||
responseHeaders.set('Content-Length', contentLength);
|
||||
}
|
||||
|
||||
const contentRange = backendRes.headers.get('content-range');
|
||||
if (contentRange) {
|
||||
responseHeaders.set('Content-Range', contentRange);
|
||||
}
|
||||
|
||||
const acceptRanges = backendRes.headers.get('accept-ranges') || 'bytes';
|
||||
responseHeaders.set('Accept-Ranges', acceptRanges);
|
||||
|
||||
const etag = backendRes.headers.get('etag');
|
||||
if (etag) {
|
||||
responseHeaders.set('ETag', etag);
|
||||
}
|
||||
|
||||
const lastModified = backendRes.headers.get('last-modified');
|
||||
if (lastModified) {
|
||||
responseHeaders.set('Last-Modified', lastModified);
|
||||
}
|
||||
|
||||
// Set aggressive caching for static media (1 year with immutable)
|
||||
responseHeaders.set('Cache-Control', 'public, max-age=31536000, s-maxage=31536000, immutable');
|
||||
responseHeaders.set('X-Content-Type-Options', 'nosniff');
|
||||
|
||||
return new Response(backendRes.body, {
|
||||
status: backendRes.status,
|
||||
statusText: backendRes.statusText,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
console.error('[Media Proxy Error]', err);
|
||||
return new NextResponse('Internal Media Proxy Error', { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function HEAD(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
) {
|
||||
try {
|
||||
const { path } = await params;
|
||||
if (!path || path.length === 0) {
|
||||
return new NextResponse(null, { status: 400 });
|
||||
}
|
||||
|
||||
const filePath = path.map(segment => encodeURIComponent(segment)).join('/');
|
||||
const backendBase = (
|
||||
process.env.INTERNAL_API_URL ||
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
'http://127.0.0.1:4001'
|
||||
).replace(/\/api\/?$/, '');
|
||||
|
||||
const targetUrl = `${backendBase}/uploads/${filePath}`;
|
||||
const backendRes = await fetch(targetUrl, { method: 'HEAD', cache: 'no-store' });
|
||||
|
||||
const responseHeaders = new Headers();
|
||||
const contentType = backendRes.headers.get('content-type') || 'application/octet-stream';
|
||||
responseHeaders.set('Content-Type', contentType);
|
||||
const contentLength = backendRes.headers.get('content-length');
|
||||
if (contentLength) responseHeaders.set('Content-Length', contentLength);
|
||||
responseHeaders.set('Accept-Ranges', 'bytes');
|
||||
responseHeaders.set('Cache-Control', 'public, max-age=31536000, s-maxage=31536000, immutable');
|
||||
|
||||
return new NextResponse(null, {
|
||||
status: backendRes.status,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
console.error('[Media Proxy HEAD Error]', err);
|
||||
return new NextResponse(null, { status: 502 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user