Tech Verse Logo
Enable dark mode
Next.js Custom Image Loader for S3 and MinIO

Next.js Custom Image Loader for S3 and MinIO

•Updated •11 min read

If the bucket is public, you don't need a loader: allow it in images.remotePatterns. For a private bucket, put a resizer such as imgproxy in front of it and write a loader that turns { src, width, quality } into an imgproxy URL like rs:fit:{width}:0. Register it with loader: 'custom' and loaderFile, and restrict sources and widths on imgproxy's side.

A custom image loader is a function that takes { src, width, quality } and returns a URL. That's all it is. next/image calls it once for every width in the srcset it generates, and the browser picks one. The work is on the other side of that URL: something has to actually produce a 640-pixel WebP of your photo, and S3 and MinIO don't. They store bytes and hand them back unchanged.

So before writing a loader, decide who does the resizing. This article walks through that decision, then builds a loader for the most common self-hosted setup (imgproxy reading straight from an S3 or MinIO bucket), tests it without a browser, and locks it down so strangers can't make your resizer render arbitrary sizes.

Do you need a custom loader at all?

Often you don't. If the objects in your bucket are publicly readable, the built-in optimizer handles them fine. Allow the bucket in remotePatterns and keep using the default loader, which fetches the original, resizes it on your Next.js server and caches the result:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    remotePatterns: [new URL('https://shop-media.s3.us-east-1.amazonaws.com/products/**')],
  },
}

export default nextConfig

The remotePatterns reference explains the matching: anything that doesn't match gets a 400 Bad Request from /_next/image, and in development you'll see Invalid src prop (...) on `next/image`, hostname "..." is not configured under images in your `next.config.js`. If MinIO runs on localhost or a private IP during development, the optimizer also refuses it unless you set images.dangerouslyAllowLocalIP: true, which exists to block SSRF into your network. Keep that flag in a development-only branch of the config.

A custom loader starts to pay off in three situations:

  • The bucket is private. The src documentation says the default optimizer doesn't forward headers when it fetches an image, so it can't authenticate to S3. Presigned URLs technically work, but each one has a different query string, which defeats every cache along the way.
  • You don't want image processing on your app servers. Resizing is CPU-heavy. On a small VPS it competes with rendering pages.
  • You already have a CDN or resizing service in front of the bucket and only need Next.js to build the right URLs.

If none of those apply, stop here and use remotePatterns. The rest of the article is for when at least one does.

How next/image calls your loader

Knowing exactly which widths the loader receives shapes the rest of the design, so it's worth a look at what next/image does with your props. The widths always come from two config arrays: deviceSizes (default 640, 750, 828, 1080, 1200, 1920, 2048, 3840) and imageSizes (default 32, 48, 64, 96, 128, 256, 384). Your loader is never asked for a width outside those lists.

  • A fixed width and no sizes produces a 1x/2x srcset. A width={64} avatar asks for 64 and 128.
  • A sizes prop produces a full w srcset across the combined list. If sizes contains vw values, widths smaller than the first device size times the smallest percentage are dropped.
  • fill without sizes uses deviceSizes only and assumes the image is as wide as the viewport.

The src attribute on the rendered <img> is the largest entry, for browsers that ignore srcset. quality is whatever you passed as a prop, or undefined if you passed nothing. The built-in optimizer treats that as 75, so your loader should pick its own default instead of writing q:undefined into a URL.

Two details trip people up. First, remotePatterns does nothing for a custom loader. The hostname check lives inside the default loader, so once you replace it, the allowlist is yours to enforce on the resizer side. Second, outside production builds next/image calls your loader once as a self-check. If the URL it gets back is the same as src, or has the same path and no query string, it logs has a "loader" property that does not implement width. A loader that returns the raw bucket URL for every width triggers that warning, and it's right: you'd be sending the 3840-pixel original to phones. If you truly can't resize, use the unoptimized prop and say so explicitly.

The resizer: imgproxy in front of the bucket

imgproxy is a single Go binary (or container) that reads an original, resizes and re-encodes it, and returns the result. It can read straight from S3 with its own credentials, so the bucket stays private and the browser only ever talks to imgproxy. MinIO speaks the S3 API, so the same setup works for both; you only change the endpoint. Thumbor or a CDN's image service would work the same way with a different URL format.

The imgproxy S3 source docs list what to set. Use a read-only access key scoped to the one bucket:

IMGPROXY_USE_S3=true
IMGPROXY_S3_ENDPOINT=http://minio.internal:9000
IMGPROXY_S3_REGION=us-east-1
AWS_ACCESS_KEY_ID=imgproxy-reader
AWS_SECRET_ACCESS_KEY=change-me
IMGPROXY_ALLOWED_SOURCES=s3://shop-media/
IMGPROXY_TTL=31536000

IMGPROXY_USE_S3 turns on s3://bucket/key source URLs. IMGPROXY_S3_ENDPOINT points at MinIO instead of AWS; leave it out for real S3. Path-style addressing is the default for a custom endpoint, which is what MinIO expects. IMGPROXY_ALLOWED_SOURCES is a comma-separated list of source prefixes, and it's the replacement for the remotePatterns check you just lost: without it, anyone could point your imgproxy at any URL on the internet. IMGPROXY_TTL sets Cache-Control: max-age on the responses and already defaults to a year.

Writing the loader

imgproxy URLs follow the shape /%signature/%processing_options/%encoded_source_url.%extension, described in the processing options reference. With signing disabled, the signature segment can be any placeholder such as _, but it has to be there. rs:fit:640:0 resizes to fit 640 pixels wide with the height worked out from the aspect ratio, q:75 sets quality, and the .webp extension picks the output format.

I encode the source as URL-safe Base64 rather than using imgproxy's plain/ form. Object keys contain spaces, @2x suffixes and non-ASCII names more often than you'd think, and the plain form requires you to escape those correctly. Base64 sidesteps the question entirely:

'use client'

import type { ImageLoaderProps } from 'next/image'

const IMGPROXY_URL = process.env.NEXT_PUBLIC_IMGPROXY_URL
const BUCKET = process.env.NEXT_PUBLIC_IMAGE_BUCKET

if (!IMGPROXY_URL || !BUCKET) {
  throw new Error('NEXT_PUBLIC_IMGPROXY_URL and NEXT_PUBLIC_IMAGE_BUCKET must be set when the app is built')
}

const base = IMGPROXY_URL.replace(/\/+$/, '')

function base64Url(value: string): string {
  const bytes = new TextEncoder().encode(value)
  let binary = ''
  for (const byte of bytes) binary += String.fromCharCode(byte)
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}

export default function bucketImageLoader({ src, width, quality }: ImageLoaderProps): string {
  const key = src.replace(/^\/+/, '')
  const source = base64Url(`s3://${BUCKET}/${key}`)
  return `${base}/_/rs:fit:${width}:0/q:${quality ?? 75}/${source}.webp`
}

A few choices in there are deliberate. The environment check runs when the module loads, not inside the loader. NEXT_PUBLIC_ variables are inlined into the browser bundle at build time, so a missing value isn't a runtime problem you can fix by restarting the server. Throwing early turns it into a failed build, where you'll notice, instead of thousands of image requests to undefined/_/rs:fit.... The trailing-slash strip on the base URL saves you from //_/ when someone sets the variable to https://img.example.com/. And the leading slash is removed from src, so "/products/hat.jpg" and "products/hat.jpg" map to the same object key.

The encoder uses TextEncoder and btoa because the loader runs in two places: on the server while rendering HTML and in the browser after hydration. Buffer only exists on the server. Both of these exist in Node and in every browser, so the same output comes out in both places and the srcset doesn't change during hydration.

Global loaderFile or a wrapper component

There are two ways to wire the loader in, and the choice depends on whether every image lives in the bucket.

If it does, register it globally. Every <Image> in the app then goes through it with no extra props:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    loader: 'custom',
    loaderFile: './lib/bucket-image-loader.ts',
  },
}

export default nextConfig

The images config reference spells out the rules: loaderFile is resolved relative to the project root and the file must have a default export. A wrong path fails as soon as the config loads, with Specified images.loaderFile does not exist at "...". A missing default export shows up when the first image renders, as images.loaderFile detected but the file is missing default export. Pairing loaderFile with a built-in loader name such as 'imgix' is also rejected; set loader: 'custom'.

The catch with the global option is that it really is global. Your logo in public/ and every statically imported image now go to the loader too, and their src values are paths on your Next.js server, not keys in the bucket. If your app mixes bucket images with local ones, don't register a global loader. Wrap the loader in a component and use it only where the image comes from the bucket:

'use client'

import Image, { type ImageProps } from 'next/image'
import bucketImageLoader from '@/lib/bucket-image-loader'

export function BucketImage(props: Omit<ImageProps, 'loader'>) {
  return <Image {...props} loader={bucketImageLoader} />
}

The wrapper has to be a Client Component. A loader is a function, and functions can't be passed as props from a Server Component to a Client Component, because they aren't serializable. With the wrapper, though, the server side only passes strings and numbers, so you can use it straight from a server page:

import { BucketImage } from '@/components/bucket-image'

export default function ProductPage() {
  return (
    <main>
      <BucketImage
        src="products/canvas tote@2x.jpg"
        alt="Canvas tote bag on a wooden table"
        width={800}
        height={600}
        sizes="(max-width: 768px) 100vw, 50vw"
        preload
      />
    </main>
  )
}

Everything else keeps using plain next/image and the built-in optimizer. I prefer this split even when most images live in S3, because it keeps the special case visible at the call site.

Testing the loader without a browser

next/image exports getImageProps, which runs the same code the component uses and returns the props it would put on the <img>. That makes it easy to check the exact srcset your loader produces in a unit test or a quick script. Here's the output for the product photo above, with the bucket set to shop-media and default sizes:

https://img.example.com/_/rs:fit:384:0/q:75/czM6Ly9zaG9wLW1lZGlhL3Byb2R1Y3RzL2NhbnZhcyB0b3RlQDJ4LmpwZw.webp 384w
https://img.example.com/_/rs:fit:640:0/q:75/czM6Ly9zaG9wLW1lZGlhL3Byb2R1Y3RzL2NhbnZhcyB0b3RlQDJ4LmpwZw.webp 640w
https://img.example.com/_/rs:fit:750:0/q:75/czM6Ly9zaG9wLW1lZGlhL3Byb2R1Y3RzL2NhbnZhcyB0b3RlQDJ4LmpwZw.webp 750w

That's three of nine entries; the 32 to 256 widths are dropped because sizes says the image is at least 50vw. Decoding the last path segment gives back s3://shop-media/products/canvas tote@2x.jpg, space and @ intact. A 64-pixel avatar with no sizes produces just rs:fit:64:0 1x and rs:fit:128:0 2x.

Then check the resizer itself with one of those URLs. You want a 200, the right content type and a long cache lifetime:

curl -sI "https://img.example.com/_/rs:fit:640:0/q:75/czM6Ly9zaG9wLW1lZGlhL3Byb2R1Y3RzL2NhbnZhcyB0b3RlQDJ4LmpwZw.webp" | grep -iE '^(HTTP|content-type|cache-control)'

If it fails, imgproxy's logs say why. The usual causes are a wrong object key, credentials that can't read the bucket, or a bucket that IMGPROXY_ALLOWED_SOURCES doesn't cover. One more behaviour to expect: rs:fit doesn't enlarge by default, so asking a 1200-pixel original for 3840 returns 1200 pixels. That's what you want, and it means the largest srcset entries cost almost nothing for small originals.

Locking widths down with presets

The loader above has a weakness you should know about. With signing disabled, the URL is the whole request, and anyone can edit it. Someone can request rs:fit:3839:0, then 3838, then 3837, and every one is a cache miss that costs your resizer a decode and an encode.

The usual fix is URL signing, but signing can't happen in a loader. The loader ships to the browser, so the key would ship with it. Signing only works if a server builds every URL, and next/image builds them on the client too.

imgproxy's presets-only mode closes the gap another way. With IMGPROXY_ONLY_PRESETS=true, the processing-options segment can only contain names from IMGPROXY_PRESETS, so arbitrary widths are rejected. Since next/image only ever requests widths from deviceSizes and imageSizes, one preset per width covers every request. Generate the list from the same arrays your Next.js config uses:

const deviceSizes = [640, 750, 828, 1080, 1200, 1920, 2048, 3840]
const imageSizes = [32, 48, 64, 96, 128, 256, 384]

const presets = [...imageSizes, ...deviceSizes].map((w) => `w${w}=rs:fit:${w}:0/q:75`)
console.log(`IMGPROXY_PRESETS=${presets.join(',')}`)

That prints a single IMGPROXY_PRESETS=w32=rs:fit:32:0/q:75,w48=... line for imgproxy's environment. The loader then emits preset names instead of options:

'use client'

import type { ImageLoaderProps } from 'next/image'

const IMGPROXY_URL = process.env.NEXT_PUBLIC_IMGPROXY_URL
const BUCKET = process.env.NEXT_PUBLIC_IMAGE_BUCKET

if (!IMGPROXY_URL || !BUCKET) {
  throw new Error('NEXT_PUBLIC_IMGPROXY_URL and NEXT_PUBLIC_IMAGE_BUCKET must be set when the app is built')
}

const base = IMGPROXY_URL.replace(/\/+$/, '')

function base64Url(value: string): string {
  const bytes = new TextEncoder().encode(value)
  let binary = ''
  for (const byte of bytes) binary += String.fromCharCode(byte)
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}

export default function bucketImageLoader({ src, width }: ImageLoaderProps): string {
  const key = src.replace(/^\/+/, '')
  return `${base}/_/w${width}/${base64Url(`s3://${BUCKET}/${key}`)}.webp`
}

The trade-off is that the quality prop no longer does anything; it's fixed per preset. Most sites use one quality everywhere anyway. If you change deviceSizes or imageSizes in next.config.ts, regenerate the presets in the same commit, or requests for the new widths will be rejected. One broken srcset entry while the others load is the symptom.

Caching and replacing images

With a custom loader, the built-in optimizer's cache and images.minimumCacheTTL no longer apply, because /_next/image is out of the picture. Caching is now whatever imgproxy's Cache-Control header says plus whatever CDN you put in front of it, and you should put one in front. imgproxy is fast, but it shouldn't be resizing the same hero image for every visitor.

A one-year TTL means you can't overwrite products/hat.jpg in the bucket and expect anyone to see the new version. Treat object keys as immutable: upload the replacement under a new key (a content hash or an upload ID in the name works well) and update the reference in your database. If those references come from a CMS or API that feeds statically rendered pages, the page HTML also needs refreshing. That's where cache tags and on-demand revalidation come in.

The loader controls widths and URLs, but the browser still picks a srcset entry based on the sizes you give it. A wrong sizes value downloads images twice as wide as needed, whichever loader you use; the guide on sizes and remote patterns covers how to get it right. And if you're adding images to the page that's your Largest Contentful Paint, use the preload prop on that one image, then measure LCP and CLS to make sure it's doing what you expect.

WRITTEN BY

Full Stack Software Engineer | Laravel · Next.js · AWS

Full Stack Software Engineer with 7+ years of experience building scalable, secure web applications with Laravel, PHP, React, Next.js, and AWS for SaaS, CRM, telecom, and e-commerce companies. Specialized in cloud telephony (FreeSWITCH, SMPP, WebRTC): increased concurrent call capacity by 40% and cut report queries to under 500 ms. Author of open-source Laravel packages with 10K+ downloads on Packagist. Led a team of 4 engineers and shipped production systems for clients in the UAE, USA, India, Saudi Arabia, and Bangladesh.

How we research, write and check articles

    Latest Posts

    View All

    Securing Linux Kernel Network Buffers Against DDoS Floods

    Securing Linux Kernel Network Buffers Against DDoS Floods

    Next.js Middleware Authentication and Token Refresh Flows

    Next.js Middleware Authentication and Token Refresh Flows

    Livewire Performance Optimization Under High Load

    Livewire Performance Optimization Under High Load

    Configuring Nginx Upstream Keepalive for Node Backends

    Configuring Nginx Upstream Keepalive for Node Backends

    Enforcing Immutable State Patterns in React

    Enforcing Immutable State Patterns in React

    FastAPI Dependency Overrides for Integration Testing

    FastAPI Dependency Overrides for Integration Testing

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream