Spaces:
Running
Running
| import { NextResponse } from 'next/server'; | |
| /** | |
| * GET /api/pdf-proxy?url=<encoded_pdf_url> | |
| * Proxies a PDF from an external URL to bypass CORS restrictions. | |
| * Returns the PDF with correct Content-Type so PDF.js can render it. | |
| */ | |
| export async function GET(request) { | |
| const { searchParams } = new URL(request.url); | |
| const pdfUrl = searchParams.get('url'); | |
| if (!pdfUrl) { | |
| return NextResponse.json({ error: 'Missing url parameter' }, { status: 400 }); | |
| } | |
| try { | |
| const res = await fetch(pdfUrl, { | |
| headers: { | |
| 'User-Agent': 'Mozilla/5.0 (compatible; AnnotationTool/1.0)', | |
| }, | |
| signal: AbortSignal.timeout(30000), // 30s timeout | |
| }); | |
| if (!res.ok) { | |
| return NextResponse.json( | |
| { error: `PDF fetch failed: HTTP ${res.status}` }, | |
| { status: res.status } | |
| ); | |
| } | |
| const pdfBuffer = await res.arrayBuffer(); | |
| return new Response(pdfBuffer, { | |
| status: 200, | |
| headers: { | |
| 'Content-Type': 'application/pdf', | |
| 'Content-Length': pdfBuffer.byteLength.toString(), | |
| 'Cache-Control': 'public, max-age=86400', // cache 24h | |
| 'Access-Control-Allow-Origin': '*', | |
| }, | |
| }); | |
| } catch (error) { | |
| console.error('PDF proxy error:', error); | |
| return NextResponse.json( | |
| { error: 'Failed to proxy PDF: ' + error.message }, | |
| { status: 500 } | |
| ); | |
| } | |
| } | |