How would you handle image failures in production?
Interview answer
When an image fails to load, replace it with a reliable local fallback from the image error handler, remove or guard that handler before changing src to prevent a fallback loop, preserve useful alt text, and record the failed URL so production failures can be diagnosed.
Plain JavaScript: try one fallback
<img id="product-photo" src="/media/product-42.webp"width="480" height="320" alt="Blue travel backpack" />
const image = document.querySelector('#product-photo');image.onerror = () => {const originalUrl = image.currentSrc || image.src;console.warn('Product image failed', { originalUrl });image.onerror = null; // remove before changing the sourceimage.removeAttribute('srcset'); // do not keep selecting a broken candidateimage.src = '/images/image-unavailable.svg';image.alt = 'Product photo unavailable';};
Install the handler before starting the load when creating images programmatically. For an existing image, install it early enough to observe the failure; attaching after a completed error misses that event. The local fallback path is illustrative: ship the asset and verify its response. If the fallback fails, the cleared handler prevents repeated replacements; useful alt text remains. Returning true is not required to handle this image event. For a picture element, source candidates may also need to be disabled or replaced.
React: a guarded fallback and a final text state
import { useState } from 'react';function ImageAttempt({ src, alt }) {const [stage, setStage] = useState('original');if (stage === 'unavailable') return <divrole="img" aria-label={`${alt} — image unavailable`}style={{ width: '100%', aspectRatio: '3 / 2', display: 'grid', placeItems: 'center' }}>Image unavailable</div>;return <imgsrc={stage === 'original' ? src : '/images/image-unavailable.svg'}alt={stage === 'original' ? alt : `${alt} — image unavailable`}width={480} height={320}style={{ width: '100%', height: 'auto', aspectRatio: '3 / 2', objectFit: 'cover' }}onError={() => setStage(current =>current === 'original' ? 'fallback' : 'unavailable')}/>;}export function ProductImage({ src, alt }) {return <ImageAttempt key={src} src={src} alt={alt} />;}
There are at most two source attempts: original, fallback, then text. A changed source mounts a new ImageAttempt so a previous failure does not permanently hide a later valid image. Defining ImageAttempt at module scope preserves its identity until the key changes. Supply a meaningful description of the original content; this product-photo example assumes a non-decorative image. For decorative images use empty alt text and make the final placeholder decorative too rather than announcing redundant content.
Reserve the space before the image loads
Explicit width and height establish the intended aspect ratio. Responsive CSS then fits the image within its container. Keep the final placeholder the same ratio so a failure does not collapse the layout. Use actual asset dimensions or a deliberate crop ratio, and do not rely on a placeholder whose dimensions happen to differ. A Next.js Image still needs an authored fallback strategy; its error callback does not automatically choose an appropriate replacement for your product.
Investigate the original failure
- Check the computed URL and
currentSrc, including responsive candidates, missing values, case sensitivity, and URL encoding. - Inspect the network response: missing deployment assets, redirects to login, expired signed access, hotlink restrictions, rate limiting, or CDN/server failures.
- Verify the production base path and asset location. A development relative path can resolve differently on a nested route or a deployed host.
- Inspect CSP
img-src, mixed content, and delivery restrictions. An ordinary cross-origin image can often display without CORS; canvas pixel access and credentialed delivery have separate restrictions. - Check content type, corrupted bytes, supported format, and optimization-service errors. A 200 HTML error page is not a valid image.
- Compare cache behavior, network conditions, and devices. Preserve a failing request's diagnostic details before replacing the URL.
What to record
An image error event does not expose the HTTP status by itself. Correlate browser observations with delivery/server logs. Record a sanitized asset ID or URL path, page/route, timestamp, selected candidate, release, and whether the fallback also failed. Strip signed query strings and sensitive identifiers; sample and deduplicate repeated events. Request IDs and response status are useful when available through the delivery system. A fallback repairs the display, but should not conceal a deployment problem from monitoring.
Interview follow-ups
- What stops the fallback from failing indefinitely?
- Does switching the source reset the failure state?
- What does the screen reader announce when the photo is unavailable?
- Where would you find the status code if the error event does not contain it?
Reviewed 1 October 2026 against MDN HTMLImageElement and MDN img.
Production image-failure checklist
A placeholder prevents a broken layout, but a production answer should also cover reliability, accessibility, performance, and debugging.
- Reserve image dimensions to prevent layout shift when the original or fallback loads.
- Host the final fallback on a dependable origin and guard against the fallback failing too.
- Log the original URL, page, CDN status, and browser so repeated failures are actionable.
- Use meaningful alt text; a decorative fallback should not create noisy screen-reader output.
Related interview practice
Related JavaScript interview topics
Continue with nearby questions from the same topic cluster.