Commit No Bug
Published on

How to Make the NextJS Image Component Work on Cloudflare

Authors
  • avatar
    Name
    nikUnique
    Twitter
An image about Cloudflare and Next.js image

The Problem

Let's imagine this situation: you host your website on some hosting provider, and then you hear that CloudFlare has a nice free plan for hosting static websites. You use Next.js for your website, and therefore also use the <Image> component from next/image for your images. You move to CloudFlare and notice that your images just do not load. If you have such a problem, then this blog post is for you, because this is exactly the problem I encountered along the way, and here I show the solution I found that solves this problem.

The Solution

The solution is taken from Next.js documentation. The first thing to do is to add some configuration to next.config.js:

next.config.js
module.exports = {
  images: {
    loader: 'custom',
    loaderFile: './loader.js',
  },
}

Then you need to create a loader file. Here is a loader.js file:

loader.js
'use client'

export default function myImageLoader({ src, width, quality }) {
  // Instead of "example.com", use your actual website domain or Cloudflare Pages/Workers domain
  return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}

Alternatively, you can use the loader prop to pass the function to each instance of next/image. This one I didn't try, but maybe you may need or want to.

GOOD TO KNOW: Customizing the image loader file, which accepts a function, requires using Client Components to serialize the provided function.

To learn more about configuring the behavior of the built-in Image Optimization API and the Image Component, see Image Configuration Options for available options.