Files
sofa/app/api/images/[...path]/route.ts
T
jakeandClaude Opus 4.6 ee723e41d6 Add TMDB image caching pipeline and resolve image URLs server-side
Introduce a local disk cache for TMDB images served through a proxy API
route (/api/images/[...path]), eliminating direct client-side CDN
dependencies. Images are cached by category (posters, backdrops, stills,
logos) and served with immutable cache headers.

Move all tmdbImageUrl() calls from client components to API routes and
server components so clients receive ready-to-use URLs. This removes the
need to expose TMDB_IMAGE_BASE_URL and IMAGE_CACHE_ENABLED via
next.config.ts env block. The landing page is split into a server
wrapper (app/page.tsx) and client component (components/landing-page.tsx).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 13:10:17 -05:00

62 lines
1.6 KiB
TypeScript

import path from "node:path";
import { type NextRequest, NextResponse } from "next/server";
import {
fetchAndMaybeCache,
type ImageCategory,
imageCacheEnabled,
} from "@/lib/services/image-cache";
const VALID_CATEGORIES = new Set<ImageCategory>([
"posters",
"backdrops",
"stills",
"logos",
]);
const IMMUTABLE_CACHE = "public, max-age=31536000, immutable";
export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ path: string[] }> },
) {
const segments = await params;
if (!imageCacheEnabled()) {
return NextResponse.json(
{ error: "Image cache disabled" },
{ status: 404 },
);
}
if (segments.path.length !== 2) {
return NextResponse.json({ error: "Invalid path" }, { status: 400 });
}
const [category, rawFilename] = segments.path;
if (!VALID_CATEGORIES.has(category as ImageCategory)) {
return NextResponse.json({ error: "Invalid category" }, { status: 400 });
}
// Sanitize filename — only allow basename to prevent path traversal
const filename = path.basename(rawFilename);
if (!filename || filename !== rawFilename || filename.includes("..")) {
return NextResponse.json({ error: "Invalid filename" }, { status: 400 });
}
const tmdbPath = `/${filename}`;
const result = await fetchAndMaybeCache(tmdbPath, category as ImageCategory);
if (!result) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
return new NextResponse(new Uint8Array(result.buffer), {
status: 200,
headers: {
"Content-Type": result.contentType,
"Cache-Control": IMMUTABLE_CACHE,
},
});
}