import { NextRequest, NextResponse } from "next/server"; export async function GET(req: NextRequest) { const { searchParams } = new URL(req.url); const url = searchParams.get("url"); if (!url) { return NextResponse.json( { error: "Missing URL parameter" }, { status: 400 }, ); } try { // Try global fetch first, fall back to node-fetch if necessary let response: any; try { if (typeof (globalThis as any).fetch === 'function') { response = await (globalThis as any).fetch(url); } } catch (e) { response = undefined; } if (!response || typeof response.ok === 'undefined' || !response.ok) { try { const mod = await import('node-fetch'); const nodeFetch = (mod as any).default ?? mod; response = await nodeFetch(url); } catch (err) { console.error('Failed to fetch image:', err); return NextResponse.json( { error: "Failed to fetch image" }, { status: 500 }, ); } } if (!response || !response.ok) { throw new Error(`Failed to fetch image: ${response?.statusText ?? 'no response'}`); } const contentType = response.headers.get("content-type"); const buffer = await response.arrayBuffer(); return new NextResponse(buffer, { headers: { "Content-Type": contentType || "application/octet-stream", }, }); } catch (error) { console.error("Failed to fetch image:", error); return NextResponse.json( { error: "Failed to fetch image" }, { status: 500 }, ); } }