proxy images through server

In my current setup where on the app side the images are fetched directly from an external source, however, now I'd like to proxy the images through my server, and cache it in the server instead of sending a fetch request to the external source. here is my app side code code
<LazyNuxtImg
:src="`api/image/${image_id}`"
alt=""
:modifiers="{ cache: 3600 }"
style="min-height: 300px;"
/>
<LazyNuxtImg
:src="`api/image/${image_id}`"
alt=""
:modifiers="{ cache: 3600 }"
style="min-height: 300px;"
/>
I don't know how to write this on the server side "server/api/image/[id].ts"
export default defineEventHandler(async (event) => {
const id = event.context.params?.id

return fetch(`https:someexternanalsrc.com/${id}`;
})
export default defineEventHandler(async (event) => {
const id = event.context.params?.id

return fetch(`https:someexternanalsrc.com/${id}`;
})
This doesn't work. On app side I get the error msg in the console error : {message: "[404] [IPX_FILE_NOT_FOUND] File not found: /api/image//sOmEimAgeidhere.jpg"} message : "[404] [IPX_FILE_NOT_FOUND] File not found: /api/image//sOmEimgAgeidhere.jpg" ... TLDR; I'm simply asking "how to proxy images through the server?"
5 Replies
kapa.ai
kapa.ai3mo ago
Hi @Thick Black W. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To proxy images through your Nuxt server, you need to create an API route that fetches the image from the external source and returns the image data as a stream or buffer, setting the correct headers so the client (and the Nuxt Image module) can handle it as an image. Your current approach is close, but simply returning the result of a fetch call won't work, because you need to handle the response as a binary stream and set the appropriate content type. Here’s how you can do it in your server/api/image/[id].ts file:
export default defineEventHandler(async (event) => {
const id = event.context.params?.id
if (!id) {
throw createError({ statusCode: 400, statusMessage: 'Missing image id' })
}

// Fetch the image from the external source
const response = await fetch(`<https://someexternanalsrc.com/${id}`>)

if (!response.ok) {
throw createError({ statusCode: response.status, statusMessage: 'Image not found' })
}

// Set the correct content type header
event.node.res.setHeader('Content-Type', response.headers.get('content-type') || 'image/jpeg')

// Optionally, set cache headers
event.node.res.setHeader('Cache-Control', 'public, max-age=3600')

// Stream the image data to the client
return response.body
})
export default defineEventHandler(async (event) => {
const id = event.context.params?.id
if (!id) {
throw createError({ statusCode: 400, statusMessage: 'Missing image id' })
}

// Fetch the image from the external source
const response = await fetch(`<https://someexternanalsrc.com/${id}`>)

if (!response.ok) {
throw createError({ statusCode: response.status, statusMessage: 'Image not found' })
}

// Set the correct content type header
event.node.res.setHeader('Content-Type', response.headers.get('content-type') || 'image/jpeg')

// Optionally, set cache headers
event.node.res.setHeader('Cache-Control', 'public, max-age=3600')

// Stream the image data to the client
return response.body
})
Key points: - You must set the Content-Type header to match the image type. - You can set cache headers as needed. - Return the response body as a stream to efficiently proxy the image. This approach will allow your Nuxt app to serve images from /api/image/:id, proxying and caching them as you wish. Note: If you want to cache the images on your server (beyond HTTP cache headers), you would need to implement a caching mechanism (e.g., saving to disk or memory), but the knowledge sources do not provide a ready-made example for that. For more on server API routes and handling responses, see the Nuxt documentation on server directory structure and API routes and forwarding context & headers. If you use Nuxt Image, make sure your <NuxtImg> or <LazyNuxtImg> component points to the correct API route, as you already do. If you encounter [IPX_FILE_NOT_FOUND], it usually means the image could not be fetched or returned properly—ensure your API route is working by testing it directly in the browser or with a tool like curl. If you need to forward headers or cookies, see the forwarding context & headers section. Let me know if you need an example for a specific caching strategy! ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1321238874634195004> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Thick Black W
Thick Black WOP3mo ago
@kapa.ai I'm getting "404 IPX_FILE_NOT_FOUND"
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- The error [404] [IPX_FILE_NOT_FOUND] File not found: /api/image/... typically means that the Nuxt Image module (using the default ipx provider) is trying to find the image in its configured source directory, but cannot locate it at the given path. From the knowledge sources: - Nuxt Image expects local images to be in the public/ directory by default. If you use a custom directory, you must set the dir option in your nuxt.config.ts to match where your images are stored. If the image is not found in the configured directory, you will get a 404 IPX error NuxtImage returning 404, Nuxt Image Providers, dir option. - Images in the assets/ directory are not processed by Nuxt Image; only those in public/ (or your configured dir) are handled Nuxt Image Providers. - If you are proxying images through an API route (e.g., /api/image/[id]), Nuxt Image's IPX provider will not automatically know how to handle this unless you implement the proxy logic yourself and ensure the route returns the image data with the correct headers. In your case: - If your API route is not returning the image data correctly (e.g., not setting the right headers, or not streaming the image), Nuxt Image will not be able to process it, resulting in the 404 IPX error. - Make sure your API route is working by visiting it directly in the browser. If it does not return the image, the problem is with your API route implementation. Summary:
The [404] [IPX_FILE_NOT_FOUND] error means Nuxt Image cannot find or access the image at the specified path. Double-check that: - The image exists in the correct directory (public/ or your configured dir). - If using an API route, it returns the image data correctly with appropriate headers. - The path you use in <NuxtImg> matches the actual accessible URL. If you need to serve images via an API route, you must ensure your server-side code streams the image data and sets the correct content type, as described in the knowledge sources. If you need a working example, see the Nuxt Image Providers documentation and the dir option. If you are still getting the error after these checks, the knowledge sources do not provide further troubleshooting steps specific to your setup. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1321238874634195004> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?