CodexBloom - Programming Q&A Platform

Next.js Image Component Caching implementing Dynamic URLs and Custom Cache-Control Headers

👀 Views: 14 💬 Answers: 1 📅 Created: 2025-06-10
next.js image api javascript

I'm attempting to set up I tried several approaches but none seem to work. I'm prototyping a solution and I've been struggling with this for a few days now and could really use some help. I'm working with a question with the Next.js Image component where dynamic images served from an API are not being cached as expected despite setting custom Cache-Control headers. My setup involves fetching images from a third-party API and passing them to the Image component in Next.js. While the images load fine initially, they seem to be fetched from the server on every page load instead of being cached. I have confirmed that the API is sending the appropriate Cache-Control headers, but the Image component doesn't seem to respect them. Here's a simplified version of my image fetching code: ```javascript import Image from 'next/image'; import { useEffect, useState } from 'react'; const DynamicImage = ({ imageUrl }) => { const [src, setSrc] = useState(''); useEffect(() => { const fetchImage = async () => { const response = await fetch(imageUrl); const blob = await response.blob(); setSrc(URL.createObjectURL(blob)); }; fetchImage(); }, [imageUrl]); return <Image src={src} alt='Dynamic Image' width={500} height={300} />; }; ``` I’ve tried a few things to resolve this scenario, including checking the Network tab in Chrome DevTools to confirm that the images are not being loaded from the cache and are instead retrieved from the network on each render. Additionally, I attempted to use the `unoptimized` prop on the Image component, but that didn’t change the behavior. I also verified that my Next.js version is 12.1.0. Does anyone have insights on how to properly cache images served from dynamic URLs with the Next.js Image component? Any help would be appreciated! My development environment is Linux. Am I missing something obvious? The stack includes Javascript and several other technologies. Any ideas what could be causing this? Hoping someone can shed some light on this.