feat: add image proxy route to serve Directus assets with auth token
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
export async function GET(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const { id } = await params
|
||||
const { searchParams } = new URL(req.url)
|
||||
const width = searchParams.get('width') || '800'
|
||||
const quality = searchParams.get('quality') || '80'
|
||||
|
||||
const directusUrl = process.env.DIRECTUS_URL!
|
||||
const token = process.env.DIRECTUS_TOKEN!
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${directusUrl}/assets/${id}?width=${width}&quality=${quality}`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
},
|
||||
)
|
||||
|
||||
if (!res.ok) {
|
||||
return NextResponse.json({ error: 'Image not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const headers = new Headers()
|
||||
headers.set('Content-Type', res.headers.get('Content-Type') || 'image/jpeg')
|
||||
headers.set('Cache-Control', 'public, max-age=31536000, immutable')
|
||||
|
||||
return new NextResponse(res.body, { status: 200, headers })
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Failed to fetch image' }, { status: 502 })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user