feat(media): implement nextjs media proxy API routes (/api/uploads & /api/media) with server-side caching and streaming
Deploy Canina / deploy (push) Successful in 1m34s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 6s

This commit is contained in:
parsa aghaei committed 2026-08-29 12:13:16 +03:30
1 parent d9c693c41b
commit fa1a35c835
19 files changed
+13806 -13030

No files matched your search

@@ -0,0 +1,113 @@
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}`;
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',
});
if (!backendRes.ok && backendRes.status !== 304 && backendRes.status !== 206) {
return new NextResponse(`Media not found or error from upstream (${backendRes.status})`, {
status: backendRes.status,
});
}
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);
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);
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 });
}
}