How to Configure the Next Image Component in next.config.{js,ts} for Optimal Performance

Configure the images object in your next.config.{js,ts} file to control the built-in optimizer, device breakpoints, image formats, and caching behavior.

The Next.js Image component delivers optimized images through a built-in optimizer that runs on the server or edge runtime. To maximize loading performance and reduce bandwidth when you configure the Next Image component within your Next config file, you must define the images object according to the Zod schema in packages/next/src/server/config-schema.ts (lines 776-840). These settings determine how the framework generates responsive srcsets, processes modern formats, and caches optimized assets across the build and runtime pipelines.

Core Configuration Options That Drive Performance

Next.js validates every images option against strict constraints at startup. The following properties directly impact how the next-image-loader (Webpack/Turbopack) and image-optimizer (runtime) process your assets:

  • loader: Selects the image source strategy (default, imgix, cloudinary, akamai, or custom). Using a CDN-based loader offloads resizing work from your server to distributed edge nodes.

  • domains / remotePatterns: Whitelists remote hosts that the optimizer may fetch. Restricting these prevents accidental fetches to slow origins and enables efficient caching of remote images.

  • deviceSizes: Defines responsive breakpoints (in px) used when the <Image> component omits explicit dimensions. Limiting this array to essential breakpoints (e.g., [640, 768, 1024, 1280, 1600]) reduces the number of generated variants and storage overhead.

  • imageSizes: Specifies fixed-size breakpoints for images with explicit width/height props. Keeping this list tight (e.g., [16, 32, 48, 64, 96]) minimizes unnecessary image generation.

  • formats: Declares desired modern formats (image/avif, image/webp). Browsers supporting these receive significantly smaller files—up to 30% smaller payloads than JPEG—reducing bandwidth and improving Core Web Vitals.

  • minimumCacheTTL: Sets the minimum cache time (in seconds) for optimized images. Longer values (e.g., 86400 for one day) reduce repeated resize work on the server.

  • quality / qualities: Controls the default JPEG/WebP quality (0-100) or defines allowed quality values. Tuning this balances visual fidelity against file size.

  • path: Customizes the base path of the internal Image Optimization API (/_next/image). Redirecting this to a CDN edge-function endpoint can lower latency for end-users.

  • customCacheHandler: Enables a user-provided caching layer implemented in the edge runtime, allowing integration with external caches like Cloudflare KV for ultra-fast responses.

  • unoptimized: Disables the optimizer entirely when set to true. Only enable this if you use an external CDN that handles its own optimization; otherwise, keep false to benefit from automatic resizing.

Practical Configuration Examples

Basic Performance-Focused Setup

This configuration leverages the built-in optimizer with sensible defaults for modern web applications:

// next.config.js
module.exports = {
  images: {
    loader: 'default',
    remotePatterns: [
      {
        hostname: 'assets.example.com',
        protocol: 'https',
        pathname: '/images/**',
      },
    ],
    deviceSizes: [640, 768, 1024, 1280, 1600],
    imageSizes: [16, 32, 48, 64, 96],
    formats: ['image/avif', 'image/webp'],
    quality: 75,
    minimumCacheTTL: 86400,
  },
};

This setup references the schema definitions for deviceSizes (lines 808-811), imageSizes (lines 818-822), formats (lines 814-817), and minimumCacheTTL (line 832) in config-schema.ts.

Third-Party CDN Integration

Offload transformation work to Imgix or similar CDNs by specifying a custom loader:

// next.config.mjs
export default {
  images: {
    loader: 'imgix',
    path: 'https://my-imgix.imgix.net',
    domains: ['my-imgix.imgix.net'],
    formats: ['image/webp'],
    deviceSizes: [640, 1024, 1600],
  },
};

According to the source code in packages/next/src/build/webpack/loaders/next-image-loader/index.ts, this configuration redirects image requests to the specified CDN path while maintaining the component's automatic srcset generation.

Advanced Edge Caching Configuration

For applications requiring custom cache handlers at the edge:

// next.config.ts
import type { NextConfig } from 'next';

const config: NextConfig = {
  images: {
    customCacheHandler: true,
    deviceSizes: [640, 1280],
    imageSizes: [64, 128, 256],
    remotePatterns: [
      {
        hostname: 'cdn.example.com',
        protocol: 'https',
        pathname: '/**',
      },
    ],
  },
};

export default config;

This advanced setup reduces variant count for faster edge generation and integrates with the custom cache handler interface defined in the schema (line 803).

Technical Implementation Flow

Understanding how configuration values flow through the system helps diagnose performance issues:

  1. Schema Validation: At build time, Next.js validates your images object against the Zod schema in packages/next/src/server/config-schema.ts. Invalid values (e.g., more than 25 deviceSizes or unsupported loaders) throw configuration errors immediately, preventing runtime performance degradation.

  2. Build-Time Processing: The next-image-loader at packages/next/src/build/webpack/loaders/next-image-loader/index.ts reads these values to transform <Image> imports and generate appropriate srcsets based on your deviceSizes and imageSizes.

  3. Runtime Optimization: The image-optimizer in packages/next/src/server/image-optimizer.ts (line 1140) uses your formats, quality, and minimumCacheTTL settings to resize, convert, and cache images on demand.

  4. Property Resolution: The utility at packages/next/src/shared/lib/get-img-props.ts builds the final image props (src, srcSet, sizes) according to the configuration, ensuring browsers receive the optimal asset for their viewport and capabilities.

Summary

  • Configure the images object in next.config.{js,ts} to control the built-in optimizer's behavior for the Next Image component.
  • Limit deviceSizes and imageSizes to essential breakpoints to reduce storage costs and cache fragmentation.
  • Enable modern formats like AVIF and WebP to deliver smaller payloads to supporting browsers.
  • Set minimumCacheTTL to at least 86400 seconds (one day) to minimize repeated image processing on the server.
  • Use remotePatterns instead of domains for granular control over external image sources, improving security and caching efficiency.
  • Select CDN loader options (imgix, cloudinary, akamai) to offload transformation work from your infrastructure.

Frequently Asked Questions

What is the difference between deviceSizes and imageSizes?

deviceSizes defines responsive breakpoints for images without explicit dimensions, typically covering viewport widths like 640px through 1600px. imageSizes defines fixed-size breakpoints for images with explicit width and height props, usually smaller values like 16px through 96px for icons and thumbnails. According to the schema in config-schema.ts, deviceSizes supports up to 25 values while imageSizes supports up to 25 distinct sizes, preventing excessive variant generation.

How does minimumCacheTTL affect image loading performance?

The minimumCacheTTL parameter sets the minimum time (in seconds) that the image optimizer caches processed images. Higher values reduce server load by preventing repeated resize and format conversion operations for popular images. The default is 60 seconds, but production applications benefit from values of 86400 (one day) or higher, ensuring that optimized assets serve instantly from cache rather than being reprocessed on each request.

Can I use the Next Image component with external CDNs without disabling optimization?

Yes. Set loader to imgix, cloudinary, or akamai rather than default, and specify your CDN base path in the path property. This configuration maintains the component's automatic srcset generation while delegating actual image transformation to the CDN. Do not set unoptimized: true unless your CDN handles all responsive image logic independently, as this disables the automatic sizing and format selection that makes the component performant.

What happens if I provide an invalid configuration value?

Next.js validates the images object against the Zod schema in packages/next/src/server/config-schema.ts during startup and build. Invalid configurations—such as unsupported loader values, malformed remotePatterns, or deviceSizes arrays exceeding 25 entries—trigger immediate build failures with descriptive error messages referencing files like errors/next-image-unconfigured-host.mdx. This strict validation prevents runtime errors and ensures the image optimizer receives only valid parameters for optimal performance.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →