REUBENREMY ARCHIVES.
← BACK TO NOTES
Today I Learned

Next.js Image Has an onError Prop

(And I Almost Did Something Embarrassing)

So there I was, staring at my code like a caveman discovering fire, about to write the most unnecessarily complex solution to a simple problem.

The Situation

I had images in three formats—.gif, .png, .jpg—and needed a fallback chain. You know, the classic "try this, if it fails, try that" dance.

My brain, in its infinite wisdom, decided this was the play:

{project?.imageFormat === 'gif' && (
  <Image src={`/images/${project?.href}/main.gif`} />
)}
{project?.imageFormat === 'png' && (
  <Image src={`/images/${project?.href}/main.png`} />
)}
{project?.imageFormat === 'jpg' && (
  <Image src={`/images/${project?.href}/main.jpg`} />
)}

I was about to add a switch statement. Maybe throw in some state management. Perhaps a useEffect to check if the file exists first? Maybe a custom hook called useImageFallbackOrchestrator?

I was this close to overengineering my way into oblivion.

Then I remembered to, you know, read the docs.

The Discovery

Turns out Next.js Image has an onError prop.

Like, just sitting there. Ready to use. Probably laughing at me.

<Image
  src={`/images/${project?.href}/main.gif`}
  onError={(e) => {
    const target = e.currentTarget;
    if (target.src.endsWith('.gif')) {
      target.src = `/images/${project?.href}/main.png`;
    } else if (target.src.endsWith('.png')) {
      target.src = `/images/${project?.href}/main.jpg`;
    }
  }}
/>
1
Component
1
Prop
3
Fallbacks

Zero switch statements. Zero shame (well, maybe a little).

The Moral of the Story

Before you brute-force your way through a problem like a developer possessed, take five seconds to check if the thing you're using already solves your problem.

Also, onError is criminally underrated. It's been there the whole time, quietly doing its job while we're out here writing dissertations in JSX.

Anyway, if you need me, I'll be over here reading docs I should've read two years ago.


P.S. - If you were also about to write a switch statement for image fallbacks, no you weren't. We never speak of this.

SCROLL